Reputation: 1023
I am using the following code to create a child process and then kill it after some time.
int pid;
if ((pid = fork()) < 0) {
printf("Error\n");
}
else if (pid == 0) {
printf("Child\n");
system("/usr/bin/./youtube-dl -o hello.mp4 http://www.youtube.com/watch?v=PDZcqBgCS74", NULL);
}
else {
printf("Father\n");
//system("ls");
printf("PId is %d",pid);
sleep(10);
kill(pid, SIGTERM);
}
The problen is that after 10 seconds the program stops but the youtube-dl process does not . It still keeps continuing. My requirement is that I want to start a process and kill it after a specified amount of time. What exactly am I doing wrong. I observe that the pidof youtube-dl which I am invoking is different from that given to my parent process from fork().
Upvotes: 0
Views: 427
Reputation: 239341
The system()
command forks off a new child process, and suspends the calling process until that child exits. When you kill your child process, the grand-child process created by system()
continues running.
Instead of system()
, use execl()
which replaces the current process with the executed file (under the same PID):
else if (pid == 0) {
execl("/usr/bin/./youtube-dl", "/usr/bin/./youtube-dl", "-o", "hello.mp4", "http://www.youtube.com/watch?v=PDZcqBgCS74", NULL);
/* only reached if execl() fails */
perror("execl");
_exit(1);
}
Upvotes: 4
Reputation: 1
IF the child process is supposed to only do the youtube download (and nothing more after), you could have simply:
else if (pid == 0) {
/* chld process */
execl("/usr/bin/youtube-dl", "youtube-dl", "-o", "hello.mp4",
"http://www.youtube.com/watch?v=PDZcqBgCS74",
NULL);
perror ("youtube-dl exec failed");
_exit(126);
}
Upvotes: 2
Reputation: 98118
When you use the system
function another process is created, whose parent is your child process. You can use exec
instead of system
so that the kill
can signal the right pid.
Upvotes: 2