Home > Software engineering >  I don't know why this program only prints "Child Complete"(UNIX)
I don't know why this program only prints "Child Complete"(UNIX)

Time:04-09

I'm a beginner of UNIX. these days I am taking a class about operating system. In lecture materials there is a code below.

#include<stdio.h>
#include<stdlib.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<unistd.h>
int main()
int main()
{
    pid_t  pid;
    //for a child program
    pid=fork();

    if (pid<0){
            fprintf(stderr,"Fork Failed\n");
            exit(-1);
    }
    else if(pid==0){//child process

            printf("I am the child %d\n",pid);    //not working
            execlp("/bin/ls","ls",NULL);
    }
    else{//parent process
            //parent will wait for the child to complete
            printf("I am the parent %d\n",pid);   //not working
            wait(NULL);
            printf("Child Complete\n");
            exit(0);
    }
}

and i expected the result of this program is (file name is fig3-9.c and execute file is a.out)

I am the child 0
a.out concurrent.c fig3-9.c, fig3-11.c
I am the parent (som value)
Child Complete

but real result is below

a.out concurrent.c fig3-9.c, fig3-11.c

Child Complete

I don't know why this program doesn't prinf("I am the child %d\n",pid) and ("I am the parent %d\n")

thanks for your helps

CodePudding user response:

you can run ok as below code.please use getpid() not pid(). man2 getpidenter link description here

#include<stdio.h>
#include<stdlib.h>
#include<wait.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
    pid_t  pid;
    //for a child program
    pid=fork();

    if (pid<0){
            fprintf(stderr,"Fork Failed\n");
            exit(-1);
    }
    else if(pid==0){//child process

            printf("I am the child %d\n",getpid());    //not working
            execlp("/bin/ls","ls",NULL);
    }
    else{//parent process
            //parent will wait for the child to complete
            printf("I am the parent %d\n",getpid());   //not working
            wait(NULL);
            printf("Child Complete\n");
            exit(0);
    }
}

run result: future@ubuntu:~/work/tmp$ ./a.out I am the parent 7383 I am the child 7384 a.out reverse_slist.c seg_ment.c unix_fork_print.c Child Complete

  • Related