Fork and exec several children in linux - c

I want to fork and exec several processes from another.
My parent code is
/*Daddy.c*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(void)
{
int status;
char *nChild;
for (int i=0; i<3;i++){
int pid = fork();
if (pid == 0)
{
sprintf(nChild, "%d", i);
printf("%d\n", i);
char *const arguments[]={nChild, NULL};
fflush(NULL);
execv("child",arguments);
printf("\nNo , you can't print!\n");
}else if (pid == -1){
printf("%d\n", getpid());
exit(0);
}
}
wait(&status);
printf("Dad %d went out!\n", getpid());
exit(0);
}
and my child process is
/*child.c*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int args, char **argv){
if( args !=2){
printf("Child going away!\n");
exit(1);
}
printf("Child %s: %d going away stylishly!\n", argv[1], getpid());
exit(0);
}
When I don´t create three forks, but one, I know how to create the child, do some work and exit from child and parent. But, in this case, with several children it seems like the child never executes.
Because of the line wait(&status) I did hope that when the first child exits, the parent also exits but, any child prints any message.
Some relevant previous questions didn´t help.

You need to make parent wait for all child processes to finish. If not, assume that 1 child waited for is done and then parent exits. What about the other 2 children? They become orphan since their parent doesn't wait for them.
pid_t wpid;
int status = 0;
.
.
while ((wpid = wait(&status)) > 0); // the parent waits for all the child processes

This code did the job
/* daddy.c */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <string.h>
int main(void)
{
int status=0;
char nChild[16];
pid_t wpid;
for (int i=0; i<3;i++){
sprintf(nChild, "%d", i);
int pid = fork();
if (pid == 0)
{
printf("%s\n", nChild);
char *const arguments[]={"child", nChild, NULL};
fflush(NULL);
execv("child",arguments);
printf("\nNo , you can't print!\n");
}else if (pid == -1){
printf("%d\n", getpid());
exit(0);
}
}
while ((wpid=wait(&status)) >0);
printf("Dad %d went out!\n", getpid());
exit(0);
}
As #OnzOg said in the comments of the question, allocation of nChild was the main problem. Also execv need pass child name twice, one as argument.
And finally, to improve the code, parent process needs to wait all processes to finish.

Related

Two child process are created. The parent process should execute until one child process terminates. How do I write this program in c?

The two child processes perform sorting by different methods. I want the parent process to wait until at least one child process terminates. This code is not giving me the required output.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
pid_t pid1, pid2;
int status;
pid1 = fork();
pid2 = fork();
if(pid1==0 && pid2 !=0)
{
//first child performing selection sort
exit(0);
}
if(pid1>0 && pid2 > 0)
{
wait(&status);
if(WIFEXITED(status))
{
printf("Parent process executed %d\n",WEXITSTATUS(status));
}
}
if(pid1>0 && pid2 ==0)
{
//second child performing bubble sort
exit(0);
}
}
pid2 = fork() is executed by the parent and the first child created from pid1 = fork(), which is not something you desire from the question description.
You might want to have something like this
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
pid_t pid1, pid2;
int status;
pid1 = fork();
if(pid1 == 0) {
//first child performing selection sort
exit(0);
}
if(pid1 > 0) {
pid2 = fork();
if(pid2 == 0) {
//second child performing bubble sort
exit(0);
}
if(pid2 > 0) {
wait(&status);
if(WIFEXITED(status)) {
printf("Parent process executed %d\n",WEXITSTATUS(status));
}
}
}
}
When you do fork(), you have a new child process starts running at the same point with the parent process. So you should make sure that only parent process calls the second fork().
Key: fork() will return 0 on child process.
Here is the way to do that:
Code
#include <stdio.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
int main(void)
{
int status;
pid_t ret, pid1, pid2;
pid1 = fork();
if (pid1 == 0) {
// First child performing selection sort
printf("Do selection sort here...\n");
sleep(5);
printf("Selection sort finished\n");
exit(0);
}
pid2 = fork();
if (pid2 == 0) {
// Second child performing bubble sort
printf("Do bubble sort here...\n");
sleep(2);
printf("Bubble sort finished\n");
// The parent must get exit code 100 from this
exit(100);
}
// Parent process waits until at least one child process terminates
do {
status = 0;
ret = wait(&status);
if (WIFEXITED(status)) {
printf("Child process %d has exited with exit code: %d\n",
ret, WEXITSTATUS(status));
break;
}
if (ret < 0) {
printf("wait() error: %s\n", strerror(errno));
break;
}
/* If we reach here, child may be traced or continued. */
} while (1);
printf("Parent has finished its waiting state...\n");
return 0;
}
Compile and Run
ammarfaizi2#integral:/tmp$ gcc -Wall -Wextra test.c -o test
ammarfaizi2#integral:/tmp$ ./test
Do bubble sort here...
Do selection sort here...
Bubble sort finished
Child process 143748 has exited with exit code: 100
Parent has finished its waiting state...
ammarfaizi2#integral:/tmp$ Selection sort finished
In this case, when a child process terminates (at least one), the parent will stop to wait. So you see "Selection sort finished" after the parent process terminates, because we simulate selection sort as 5 seconds work, and bubble sort as 3 seconds work.

How do find the granchild pid in C?

I am trying to code a toy process manager and was wondering how do I find the grandchild pids when one of my children pids dies. I.e. how to deal with the "Readiness protocol".
systemd has the "Type=forking" option, which as far as I understand, waits for the forked pid to die and then assumes that one of the forked pid's children is the actual "daemon" to monitor.
My code so far is as following, but I am missing the XXX
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/prctl.h>
int
main (int argc, const char *argv[])
{
printf("sup stared\n");
int pid;
prctl(PR_SET_CHILD_SUBREAPER);
pid = fork();
if (pid == 0) {
setpgid(0, 0);
printf("service started, pid: %d, pgid: %d\n",
getpid(), getpgid(0));
int dpid;
dpid = fork();
if (dpid == 0) {
printf("daemon started, pid: %d, pgid: %d\n",
getpid(), getpgid(0));
while (1);
}
printf("service exiting\n");
return 0;
} else {
printf("service pid: %d\n", pid);
int rc;
rc = waitpid(pid, NULL, 0);
printf("service exited? %d\n", rc);
int dpid;
dpid = XXcX();
printf("daemon, %d\n", dpid);
}
return 0;
}

Why does this function produce so many child processes?

I wrote this code in order to calculate the factorial of a number using processes and pipe(). I wanted to pass on the result from the child process to the child process. For example, to create calculate 5! the main which is the father sends the number 1 in the pipe. Then the first child is created and does 1*2, then it pushes in the pipe the number 2, the second child does 2*3 pushes the result in the pipe etc... Also, I use argv[1][0] thinking that we run the program like this (./ex3 5) where 5 is the number of which the factorial we would like to find. After running the program though, I noticed that a lot of child process was created (I only wanted 4). Why is that?
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
int fd[2];
int w,count=2;
void child_creator(){
pid_t child;
child=fork();
if (child==0) {
close(fd[1]);
read(fd[0],&w,sizeof(w));
close(fd[0]);
w=w*count;
count++;
printf("I am child %d , my father is %d , the prod is %d\n",getpid(),getppid(),w);
sleep(1);
close(fd[0]);
write(fd[1],&w,sizeof(w));
close(fd[1]);
}
}
int main(int argc , char **argv){
int fact=argv[1][0]-'0';
pipe(fd);
w=1;
for (int i=0; i<fact-1; i++){
printf("this is i %d\n", i);
child_creator();
}
return 0;
}
After a suggested answer I tried this code:
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
int fd[1000][2];
int w,count=1,j=0;
void child_creator(){
pid_t child;
j++;
pipe(fd[j]);
child=fork();
if (child==0) {
close(fd[j-1][1]);
read(fd[j-1][0],&w,sizeof(w));
close(fd[j-1][0]);
w=w*count;
printf("I am child %d , my father is %d , the prod is %d\n",getpid(),getppid(),w);
sleep(1);
close(fd[j-1][0]);
write(fd[j][1],&w,sizeof(w));
close(fd[j][1]);
exit(0);
}
}
int main(int argc , char **argv){
int fact=argv[1][0]-'0';
w=1;
for (int i=0; i<fact-1; i++){
count++;
child_creator();
sleep(2);
}
return 0;
}
Both the parent and child are returning to the for loop in main(). Since the child doesn't need to do anything after it writes its result, it should just exit rather than returning.
You also have problems with your handling of the pipe file descriptors. You do close(fd[1]) at the beginning of the child, but later try to write(fd[1],&w,sizeof(w)). You can't write to a closed FD. You don't need to close anything until the child is exiting, and exiting a process automatically closes all its files.
void child_creator(){
pid_t child;
child=fork();
if (child==0) {
read(fd[0],&w,sizeof(w));
w=w*count;
count++;
printf("I am child %d , my father is %d , the prod is %d\n",getpid(),getppid(),w);
sleep(1);
write(fd[1],&w,sizeof(w));
exit(0);
}
}

Fork Tree C Programs

I'm trying to create fork tree diagram, but still with no success. Here is my code:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
void procStatus(int level) {
printf("L%d: PID[%d] (PPID[%d])\n", level, getpid(), getppid());
fflush(NULL);
}
void levelFork(int *level) {
if (fork() == 0)
(*level)++;
wait(NULL);
}
void main() {
int level = 0;
procStatus(level);
levelFork(&level);
procStatus(level);
}
I want to create like this picture below:
And this is output look like:
Any help would be appreciated.
Code will be like this, you should fork two child for every new child process until reached target depth level ,after forking two child,parent process must exit system, only new child process should create new processes ,
you can discard parent processes by looking childpid(return value of fork)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <math.h>
int main(int argc, char *argv[])
{
pid_t childpid;
int i, n;
if (argc != 2) {
fprintf(stderr, "Usage: %s n\n", argv[0]); return 1;
}
n = atoi(argv[1]);
childpid=-1;
for (i = 1; i <= n; i++){
int b;
for(b=0;b<2;b++)
{
childpid=fork();
if (childpid <= 0) break;
}
if (childpid > 0) break;
}
while(wait(NULL) > 0) ; /* wait for all of your children */
fprintf(stderr, "i:%d process ID:%ld parent ID:%ld child ID:%ld\n",i, (long)getpid(), (long)getppid(), (long)childpid);
return 0;
}
output of code is this
└──╼ $./fork.o 2
i:3 process ID:23913 parent ID:23911 child ID:0
i:3 process ID:23915 parent ID:23911 child ID:0
i:3 process ID:23914 parent ID:23912 child ID:0
i:3 process ID:23916 parent ID:23912 child ID:0
i:2 process ID:23911 parent ID:23910 child ID:23915
i:2 process ID:23912 parent ID:23910 child ID:23916
i:1 process ID:23910 parent ID:23277 child ID:23912
You need a way of specifying the max depth and then using that to fork new processes. Once you are done with the forking you can start the printing. The snippet below should work
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
void procStatus(int level) {
printf("L%d: PID[%d] (PPID[%d])\n", level, getpid(), getppid());
fflush(NULL);
}
void levelFork(int *level,int maxlevel) {
int locallevel= *level;
while(locallevel!=maxlevel){
int pid = fork();
if (pid == 0){
(*level)++; // childs level is higher
levelFork(level,maxlevel);
return;
}
locallevel++;
wait(NULL);
}
}
void main() {
int level = 0;
int maxlevel=3;
levelFork(&level,maxlevel);
procStatus(level);
}

Calling every child process at once to kill?

I have to write an program which will generate a random amount of processes, and then will kill them one after one, after they all were created.
My problem is that I can't stop the child processes after being created.
Also, I try to call the termination-output to stdout from a child process, but don't really know how to solve it (because pid = 0 is for every child process).
#define _POSIX_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <time.h>
#include <signal.h>
#include <sys/wait.h>
int main(int argc, char const *argv[])
{
//int status;
srand(time(NULL));
int amount = (rand())%9+1;
pid_t fatherid = getpid();
printf("Hello I am a parent process, my PID is %d and I will now create %d children.\n",fatherid,amount);
pid_t pid = 1;
pid_t pidarr[amount];
for(int i = 0;i<amount;i++){
if(pid != 0){
pid = fork();
pidarr[i] = pid;
if(pid ==0){
printf("Hello I am a child process, my PID is %d and my parent has the PID %d.\n",getpid(),fatherid);
}
sleep(1);
}
}
if(pid != 0){
wait(NULL);
}
for(int i = (amount-1);i >= 0;i--){
if(pidarr[(i-1)] != 0){
printf("Hello I am a child process %d, I will terminate now.\n",getpid());
}
sleep(rand()%4);
if(pid != 0){
kill(pidarr[i],SIGKILL);
printf("Child Process %d was terminated.\n",pidarr[i]);
}
}
if(pid != 0){
printf("All child processes were terminated. I will terminate myself now.\n");
}
return EXIT_SUCCESS;
}
the following code shows how to handle fork and child processes.
the code compiles cleanly, is tested and works
#define _POSIX_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <time.h>
#include <signal.h>
#include <sys/wait.h>
int main( void )
{
//int status;
srand(time(NULL));
int amount = (rand())%9+1;
pid_t fatherid = getpid();
printf("Hello I am a parent process, my PID is %d and I will now create %d children.\n",fatherid,amount);
pid_t pid;
pid_t pidarr[amount];
for(int i = 0;i<amount;i++)
{
pid = fork();
if( -1 == pid )
{ //then, fork() error
perror( "fork() failed" );
exit(1);
}
// implied else, fork() successful
//pidarr[i] = pid;
if(!pid )
{ // then child process
printf("Hello I am a child process, my PID is %d and my parent has the PID %d.\n",getpid(),fatherid);
exit(0); // exit child process
}
// implied else, parent process
pidarr[i] = pid;
sleep(1);
} // end for
for(int i = (amount-1); i >= 0; i--)
{
kill(pidarr[i],SIGKILL);
printf("Child Process %d was terminated.\n",pidarr[i]);
}
printf("All child processes were terminated. I will terminate myself now.\n");
return(0);
} // end function: main
I am not sure about other parts of your logic (e.g. the if clause inside the fork loop), but
if(pid != 0){
wait(NULL);
}
looks suspiciously as of the parent process waits for a child to exit so that it doesn't get to the code which would kill the children at all (unless they exit on their own, but then the killing seems pointless).
Some issues in your code:
1) As #Peter Schneider points out,
parent process waits for a child to exit so that it doesn't get to the code which would kill the children
So first of all, you have to get rid of:
if(pid != 0){
wait(NULL);
}
2) The for loop that kills the children has to be executed only by the parent process, so the if clause embraces the for:
if(pid != 0){
for(int i = (amount-1);i >= 0;i--){
kill(pidarr[i],SIGKILL);
printf("Child Process %d was terminated.\n",pidarr[i]);
}
}
3) The child processes have to wait doing something until parent kills them, so append the following else clause to the above if:
else{
while(1){
printf("I am a child process %d. Will sleep for 2 senconds\n",getpid());
sleep(2);
}
}
4) the following code makes no sense, because when children are killed they simply stop working.
if(pidarr[(i-1)] != 0){
printf("Hello I am a child process %d, I will terminate now.\n",getpid());
}
If you want children to do something when the signal from kill() gets to them, you will have to use signals.

Resources