Question

I am trying to execute LP to print a PDF document and wait for it to exit. After it exists i am trying to delete the file with unlink();

However the wait finishes even before execv execute LP. I am not quite sure how to handle this and why the wait isn't waiting till execv finishes.

Is there any other way to accomplish this?

        if(fork())
        {
            fprintf(stderr, "Executing command %s %s", "/usr/bin/lp", homedir);
            char *const parmList[] = {"/usr/bin/lp", homedir, (char *)0};
            execv("/usr/bin/lp", parmList );

        }else
        {
            int pid, status;
            fprintf(stderr, "Wait\n");
            pid = wait(&status);
            fprintf(stderr, "Finished waiting.\n");
            unlink(homedir);
        }

When executing the above code the ouput would look like this:

Wait
Finished waiting.
Executing command /usr/bin/lp /home/user/Docs/test.pdf
/usr/bin/lp: Error - unable to access "/home/user/Docs/test.pdf" - No such file or directory
Was it helpful?

Solution

fork() returns zero in the child process, and a positive value in the parent process (assuming the fork succeeds), and wait(...) only makes sense in the parent process, so you need to swap the contents of your if and else blocks.

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