0

I am new to C programming. I am trying to run a program given by the path specified by the user using the fork(), exec(), and waitpid() commands. I have been trying to get this to run correctly for hours now and I keep getting errors I am not sure how to troubleshoot, as soon as I solve one error, new ones arise. I was wondering if someone can help me understand why my implementation does not work smoothly?

Many thanks

#include <stdio.h>
#include <string.h>
#include <stdlib.h>


int main(void)  {
    char command1[256], command2[256], path[556];
    printf("# ");
    scanf("%s", command1);
    scanf("%s", command2);
    scanf("%s", path);
    if(strcmp(command1,"quit")==0)
        exit(0);
    else if(strcmp(command1, "run")==0 && strcmp(command2, "command")==0){

            printf("%s", path);

            pid_t process;

            process = fork();

            //fork error
            if (process < 0){
               perror("fork");
               exit(0);
            }
            else if (process > 0){  //this is the parent process
               execl(path, "sh" , "-c", ":ls -l *.c", 0);
            }
            else {//this is the child process
               waitpid(process); //waits until the program terminates 
            }

    }




return 0;

}
10
  • And what are the error messages? Commented Feb 8, 2013 at 23:20
  • 1
    1. #include <unistd.h>, #include <sys/wait.h> and #include <sys/types.h>, then pid_t waitpid(pid_t pid, int *status, int options);. 2. waitpid waits for children to terminate, so you should exec in the child and wait in the parent. Commented Feb 8, 2013 at 23:21
  • @DanielFischer, when I follow step 1, I get an error saying that there is no such file or directory. Commented Feb 8, 2013 at 23:24
  • Looks like you got the terms "parent" and "child" reversed. Commented Feb 8, 2013 at 23:25
  • 2
    @MHZ What's your OS? Unless Windows, check the man pages for fork and waitpid. If Windows, iirc, there is no fork. Commented Feb 8, 2013 at 23:26

1 Answer 1

2

It looks to me like you have things swapped. With fork/exec, you generally do the exec in the child process, and the waitpid in the parent process.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the reply. After swapping, I am still getting an 'Linker Error' error that says that I have an undefined reference to _fork.
@MHZ: Windows does not have a fork() function, see my comment above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.