Robert Munroe
Robert Munroe

Reputation: 35

Printf() while using system calls

The homework problem I am working is pretty simple, but I'm new to C so I may be getting stuck on syntax errors. What I am trying to do is call a program from a different program, assign a new process using fork(), and then wait on the child to finish using waitpid(). I am trying to A. get waitpid() to work, and B. get a simple test message to show after the child is finished.

./countprimes is being ran remotely through ./countmaster. ./countprimes works fine, that just prints to the screen all of the primes from x to y. ./countmaster calls ./countprimes.

#include <unistd.h>
#include <stdio.h>

int main(int argc, char* argv[]){

         int processid = fork();
         int status;
         char* arguments[4];
         arguments[0]="./countprimes";
         arguments[1]="10";
         arguments[2]="30";
         arguments[3]=NULL;

         if(processid == 0)
                  execvp("./countprimes",arguments);
         else
                  waitpid(processid, &status, 0);
                  printf("test1");
}

I would expect to see: count primes instance starting at 10 and ending at 29 count primes instance for 10 to 29 is 6 test1

what I see instead is no test1 message. I also get a gcc warning: implicit declaration of function 'waitpid'; did you mean 'getpid'?

Upvotes: 1

Views: 223

Answers (1)

ddon-90
ddon-90

Reputation: 2976

I can see few syntax mistakes and a missing header:

    #include <unistd.h>
    #include <stdio.h>
    #include <sys/wait.h>

    int main(int argc, char* argv[]){

             int processid = fork();
             int status;
             char* arguments[4];
             arguments[0]="./countprimes";
             arguments[1]="10";
             arguments[2]="30";
             arguments[3]=NULL;

             if(processid == 0) {
                      execvp("./countprimes",arguments);
            } else {
                      waitpid(processid, &status, 0);
                      printf("test1");
            } 
    }

Upvotes: 2

Related Questions