SUM DIM
SUM DIM

Reputation: 3

Writing a shell in c, question about ($?) value

I am working on writing a shell in c. One of my buildin I have to implement is 'echo', I wonder how do I get the value of $? if my command were such as 'ls filename ; echo $?'. In this case, I have to use fork to create a new process and use execv to run binary ls in the system, after execute ls, how do I know the exit status of ls?

Upvotes: 0

Views: 73

Answers (2)

Zan Lynx
Zan Lynx

Reputation: 54345

Instead of waiting for a particular PID you can wait for any PID in a few ways. You can install a signal handler for SIGCHLD and in the handler call wait(&status) and it will return the PID and store the process exit status.

Or you can install a signal handler using sigaction and the SA_SIGINFO flag. Then the signal handler will have an extended signature which includes a siginfo_t* parameter and for a SIG_CHLD signal it will contain the PID and the status.

Or instead of a signal handler, you can use wait or waitpid (with a PID of -1) to wait for any process and it will return the PID of whichever one exited. Assuming your program is tracking how many children it forked, you'd handle that process exit and go back to waiting for whatever is next.

Waiting for any exit is important if your shell has job control which allows running and tracking the state of any number of background processes.

Upvotes: 0

ruakh
ruakh

Reputation: 183456

After the call to fork, the parent process needs to wait for the child process to complete. It most likely does this using waitpid. When it calls waitpid, it can pass a pointer a memory location where it wants to get the "status information" of the child process, including its exit status. See the waitpid documentation for details about how to interpret the "status information".

Upvotes: 1

Related Questions