You say you want the child to
wait main process to return to its main function
. That's a bit hard to follow, but I think you mean that you want the child to wait until its parent process returns to the caller of the function in which the fork()
was performed. It's unclear whether the caller is expected to be that process's main()
function, but that doesn't actually make any difference.
However, no function can exert direct control over what happens when it returns. The best it can do is perform some action immediately before it returns.
Moreover, since the function you present is not main()
, there is no reason to suppose that the parent process terminates when it returns from that function. Until it does terminate, the child process will remain its child, and therefore will not observe itself being inherited by process 1.
Since the program in fact is not working as you expect, I suppose that the parent process indeed is not terminating, so you need a different approach. Specifically, you need some form or other of inter-process communication (IPC). There are several flavors to choose from, and as a bonus, many of them do not require the child to busy-wait. Among the more likely options are
- a process-shared mutex or semaphore
- a signal
- a pipe
Of those, I'd recommend the last. It could look like this:
void otherplacecall(){
int pfd[2];
pid_t pid;
char c;
if (pipe(pfd)) {
// ... handle error in pipe() ...
return;
}
switch(pid = fork()) {
case -1:
// (parent) ... handle error in fork() ...
break;
case 0:
// child
printf("child: my process id is %d\n", (int) pid);
if (close(pfd[1])) {
// ... handle error in close() ...
_Exit(1);
}
if (read(pfd[0], &c, 1) < 0) {
// ... handle error in read() ...
}
puts("child: received the signal to proceed");
puts("child: I terminating");
_Exit(0);
default:
// parent
close(pfd[0]);
puts("parent: my son, take care of yourself");
close(pfd[1]); // this will cause the child's read() to return
}
}
Among the characteristics of this approach is that if the parent does terminate then its copies of the pipe ends will be closed, even if it does not close them explicitly, so the child will then proceed. That won't happen under some other circumstances, such as if the child is awaiting a signal, and the parent dies before sending it.