So for an assignment we’re required to build a shell that, among other things, emulates the & command line operator.
I’ve got the forking/exec-ing down, the issue is that calling waitpid with WNOHANG causes my program to hang after the execv has terminated. Once I hit enter the prompt comes back and the program works as normal. Note that this doesn’t occur with a blocking waitpid.
Here’s the pertinent code:
782 pid_t child = fork(); //Create child process
783
784 char** charArgs = toCharMatrix(*args);
785
786 //If creation failed, say so
787 if(child == -1) {
788 fprintf(stderr, "Error: Could not create child process.\n");
789 return -1;
790 }
791 else if(child == 0) { //else: child process code
792
793 //If the given command can be executed, attempt to exectue it
794 if(access(charArgs[0], X_OK) == 0)
795 execv(charArgs[0], charArgs);
796 else { //Else tell the user that they are an idiot
797 fprintf(stderr, "%s is not a valid path.\n", charArgs[0]);
798 return -1;
799 }
800
801 _exit(0);
802 }
803 else
804 waitpid(-1, NULL, WNOHANG);
I’ve tried a number of things in the last else statement (parent process code) from returns, to basically anything. Nothing seems to help. Once again, simply removing the WNOHANG option fixes the problem, but does not comply with the assignment specifications.
I also call waitpid(-1, NULL, WNOHANG); in the master loop right before the prompt is displayed to avoid any zombie children. This stupid carriage return issue is the only remaining problem. Thanks in advance.
It’s very unlikely it actually hangs at waitpid. Try printing return code (and errno or strerror(errno)) of waitpid call. Your snippet does not show where it hangs. Most likely reason for program wanting a return press is, you call a function which reads stdin (or parent process does blocking wait, and child waits for return press).