I’m trying to write a program in which a program continuously takes in a user input through a while loop, and in each loop forks a new child of the current program process while running a shell script. This is what I currently have:
int main(int argc, char **argv)
{
while(!feof(stdin)){
printf("Port Number:");
fgets(portno, 100, stdin);
input[strlen(portno) - 1] = '\0';
pid_t pid = fork();
if (pid < 0){
die("fork did not work");
} else if (pid == 0){
fprintf(stderr, "[pid=%d] ", (int)getpid());
fprintf(stderr, "process started on port %s\n", portno);
execl("./netcattest.sh", "netcattest.sh", portno, (char *)0);
die("program failed");
} else {
/*
if (waitpid(.... NEED HELP ON THIS PART
*/
fprintf(stderr, "[pid=%d] ", (int)pid);
fprintf(stderr, "program terminated\n");
}
}
return 0;
}
My problem is reading the waitpid documentation, I’m slightly unclear as to how to use the function. What I want to happen is when the program is a parent process, I want to be able to somehow identify all processes that have been currently terminated.
For example, if I ran the loop 3 times, and somewhere after the second loop the first process terminates, i want to somehow be able to identify the pid of the process that terminated.
I know it involves using the WNOHANG option, but I’m really confused as to how it works.
Thank you guys very much.
EDIT: Also, is there a quick way to do the 4 indents for a piece of code rather than just spacing every line individually?
I’ve never used this functionality, but my understanding of the documentation is that you should do the following:
at this point,
pidwill be -1 for error, 0 if no process has exited, or otherwise the PID of a process which has exited (chosen arbitrarily; to wait for all the processes, just keep calling it). You can examinestatuswith the various macro functions specified on the man page to determine how the process ended and what its exit code was.