Reputation: 45
I am trying to use the clone system call and sometimes the program won't end. This program just creates a new process using clone and tries to execute the cat command. Here is the program:
#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
int childFunc(void*arg)
{
char* paramlist[] = {"/bin/cat", "test.txt", NULL};
execv("/bin/cat",paramlist);
_exit(1);
}
int main(void) {
int STACKSIZE = 65536;
void* stack;
stack = malloc(STACKSIZE);
int ret = clone(childFunc, stack + STACKSIZE, 0, NULL);
waitpid(ret, NULL, 0);
free(stack);
return 0;
}
Upvotes: 1
Views: 77
Reputation: 48572
When you use clone
to create a new process that you later wait
on, you need to either pass SIGCHLD
in flags
to clone
(recommended, unless you want to change what signal gets sent on purpose) or pass __WALL
or __WCLONE
in options
to waitpid
. See man 2 clone
and man 2 waitpid
for more details. Since you weren't doing this, the waitpid
syscall was failing due to not having anything to wait on instead of waiting for the child process to complete. This resulted in the contents of test.txt
being printed after your shell prompt, which made you think it was still running, even though it wasn't. You would have noticed this if you checked the result waitpid
returned.
Upvotes: 2