Execute and terminate an executable program in Linux C program

Source: Internet
Author: User

Execvp () is available for executing and terminating an executable program ():

Run:
Char * Arg [] = {"snmpd", "-C snmpd. conf "};
Execvp (ARG [0], Arg []);

Killall termination:

If (find_pid_by_name ("dnsmasq") <0)
Return ret;
Char * Arg [] = {"killall", "-9", "snmpd "};
 
Execvp (ARG [0], Arg []);

The find_pid_by_name () implementation is as follows:
/* From busybox find_pid_by_name.c */
Int find_pid_by_name (char * pidname)
{
Dir * dir;
Struct dirent * next;
Pid_t * pidlist = NULL;
Int I = 0;

Dir = opendir ("/proc ");

While (next = readdir (DIR ))! = NULL ){
File * status;
Char filename [read_buf_size];
Char buffer [read_buf_size];
Char name [read_buf_size];

/* Must skip ".." since that is outside/proc */
If (strcmp (next-> d_name, "..") = 0)
Continue;

/* If it isn't a number, we don't want it */
If (! Isdigit (* Next-> d_name ))
Continue;

Sprintf (filename, "/proc/% S/status", next-> d_name );
If (! (Status = fopen (filename, "R "))){
Continue;
}
If (fgets (buffer, READ_BUF_SIZE-1, status) = NULL ){
Fclose (Status );
Continue;
}
Fclose (Status );

/* Buffer shoshould contain a string like "Name: binary_name "*/
Sscanf (buffer, "% * S % s", name );
// Printf ("buffer = [% s] Name = [% s]/n", buffer, name );
If (strcmp (name, pidname) = 0 ){
/*
Pidlist = realloc (pidlist, sizeof (pid_t) * (I + 2 ));
Pidlist [I ++] = strtol (next-> d_name, null, 0 );
*/
Closedir (DIR );
Return 0;
}
}

If (DIR)
Closedir (DIR );
Return-1;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.