waitpid not working- efault error

868 views Asked by At

I am trying to make a fork that runs an exec in one file and then waits for it to be finished. If the exec in the child process is terminated by a signal I want to print the signal, if the program takes too long to run I want to print timeout.

        pid_t pid;
        pid = fork();

        if(pid == 0) {
            //child process
        }
        else {
            alarm(timeout);
            int status;
            if(wait(pid, &status, 0) == pid) {
                alarm(0);
                fpw = fopen(testreport, "a+");
                if(WIFSIGNALED(status)) {
                    fprintf(fpw, "Run time errors: signal %d\n", WTERMSIG(status);
                }
                else {
                    fprintf(fpw, "Run time errors: none");
                }
                fclose(fpw);
            }
            else {
                alarm(0);
                kill(pid, SIGTERM);
                fpw = fopen(testreport, "a+");
                fprintf(fpw, "Run time errors: timeout\n");
                fclose(fpw);
            }
        }

Testreport is a previously declared char * for a file name. The waitpid isn't working though. When I print the value of the waitpid and the errno resulting I get -1 and 14, respectively. I looked up errno 14 and it's an EFAULT, which would indicate that the address of status isn't valid. How can that be so?

2

There are 2 answers

0
Rox On

Suggestions:

  1. add -Wall to your gcc parameters.

  2. More error check. In your codes fork() may return -1, and -1 is a valid input for waitpid, which may due to different behavior.

0
Greg Hewgill On

The problem is likely this line:

        if(wait(pid, &status, 0) == pid) {

Here, you are calling wait() which takes only one parameter. It looks like you intended to call waitpid(), which takes three parameters (also, in your question title you are asking about waitpid()). If you call wait() with three parameters, then the results may be unpredictable and could certainly lead to the problems you observe.