Parent trying to read children exit status (or return value), fork and wait

夙愿已清 提交于 2019-12-11 19:09:12

问题


I'm confused. Supposedly, basing on man, and many other sources, like this: Return code when OS kills your process wait(&status) should make it possible for me to get the exit status or return value of a child process?

Those 2 snippets of code, should allow me to see the exit value of it's child, and then print it. child process function:

    int childFunction(char in[],char logPath[]){
        FILE *logFile= fopen( logPath, "a" );
        if(logFile==NULL)
        return 1;
        int c=system(in);
        fclose(logFile);
        return(c);
    }

and main:

        {...some unimportant code before this}
        result= fork();
        if(result==0){
            exit(childFunction(inLine,logPath));
        }
        else if(result>0){
            int status=0;;
            int c=(int)waitpid(-1,&status,0);
            printf("a:%d b:%d\n",status, WIFEXITED(status));
        else
            return -1;
        i=0;

I tried going with wait, sleeping for some time, exiting, returning, and read man page a few times. There either is a basic error in my understanding of this function, or after 4 hours of looking I simply no longer can see it.

SOLVED For some reason, which i absolutely do not understand, if you change the return(c) in childFunction to if(c!=)return(1);else return(0) it will work. No idea why.

SOLVED 2 Okay, now I think I know why. See, it appears that either return call, or wait, reduces status to 8 most significant bits (256). What does that mean? That means, if you send normal int, the first bits are used, while the last 8 are discarded. At the same time, when I specify return (1) compiler automatically "shortens" the int to short int. Solution is to either return a short number, or do it like I did in previous "Solved" comment.


回答1:


the problem is you are not waiting for the child to exit

int c=(int)waitpid(-1,&status,WNOHANG);

Here the parent process checks if the child process has exited and if the child has not exited it returns.

In the above case, since you are opening a file in child process,there is a greater probability that there is a IO wait at child and so the parent process would be executed.

Now the parent process would check the status and since WNOHANG is used it will not be blocked at the waitpid and it continues and this is the reason you are not getting the correct status

I would suggest you use

int c=(int)waitpid(&status);


来源:https://stackoverflow.com/questions/15643502/parent-trying-to-read-children-exit-status-or-return-value-fork-and-wait

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!