Question

I'm forking, and executing a certain block in the child process. My problem is that my child process never gets into the if statement. Why is this?

if((x = strcmp(subargs[next_redirect], ">")) == 0)
            {
                pid = fork();
                fprintf(stderr, "my PID is %i\n", pid);
                if(pid == 0)
                {
                    fprintf(stderr, "the name of our file is %s\n", subargs[i+1]);
                    fp = creat(subargs[i+1], S_IWUSR | S_IRUSR);
                    dup2(fp, STDOUT_FILENO);
                    close(fp);
                    //create sub-command
                    makesubcommand(subcommand, subargs, last_redirect + 1, i);
                    execvp(subcommand[0], subcommand);
                }
                last_redirect = i;
                next_redirect = getnextredirect(subargs, i+2, subargc);
            }

My output is

my PID is 11080
my PID is 0

When you fork, the child process receives a PID of 0, correct?

My problem is at if(pid == 0){}. The code in that block never executes.

Was it helpful?

Solution 3

Apologies. It turns out that my problem was

fprintf(stderr, "the name of our file is %s\n", subargs[i+1]);

I was left thinking that the block was never executed because this wouldn't print anything. it turns out that there is a problem with subargs. I appreciate all the help.

OTHER TIPS

Your child process is not getting to if because of wait() system call.

The system call wait() blocks the calling process until one of its child processes exits or a signal is received.wait() takes the address of an integer variable and returns the process ID of the completed process. Some flags that indicate the completion status of the child process are passed back with the integer pointer. One of the main purposes of wait() is to wait for completion of child processes.

The execution of wait() could have two possible situations.

  • If there are at least one child processes running when the call to wait() is made, the caller will be blocked until one of its child processes exits. At that moment, the caller resumes its execution.

  • If there is no child process running when the call to wait() is made, then this wait() has no effect at all. That is, it is as if no wait() is there.

So remove the wait() system call. and your program will run ok.

Check the call of execvp in your code, which may have errors. You can check the return value of wait to get the child pid or -1.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top