Reputation: 9
I am writing a program for creating a shell which handles basic functionalities such as executing basic commands,piping,redirection,executing background process.However i am not being able to kill a background process, i need to know the pid() of the background process so that i can send a kill call along with the pid.Any idea how to get the pid() of a background process from a c pogram? For running the commands I am taking input from commandline into an array,parsing it and putting the command in arr[0] and the subsequent arguments in the subsequent indexes,i am taking the PATH of the system into another array and storing them as strings by using strtok and delim option as :,after this i am concatenating the path with the command,and then doing an execv().
I am stuck with this part where i have to kill a background process.Any suggestion would be extremely helpful.
Thanks in advance.
Upvotes: 0
Views: 443
Reputation: 976
You can call getpid() (in the childprosses), or the pid of the child is returned to the parent when calling fork()
Upvotes: 0
Reputation: 13728
You should do something like this:
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main()
{
pid_t pID = fork();
if (pID == 0) {
execl("/bin/ls", "/bin/ls", "-r", "-t", "-l", (char *) 0);
} else {
waitpid(pID, NULL, 0); // wait for child process
}
}
Upvotes: 1
Reputation: 989
fork
returns the PID of the child in the parent process, store it someplace and then use it to kill?
Upvotes: 1