Tran Van Boi Tran Van Boi - 1 year ago 66
C Question

how to check if execl() is success (multiple process)

I created multiple child processes by fork() and had them run executable file by execl().

I want to check if there is any execl() that is failed (ex: try to execute non-exist file). By, try to execl() all the programs and if one of them is failed then return 1 before start communicates with any programs.

here is reference code, (assume all the setups are correct)

char** exeFile = {"./p1", "./p2", "./p3", "nonexist"); //"nonexist" is a non-exist program
int main(int argc, char** argv){
pid_t childPID [numberOfChild];

for (int i = 0; i<numberOfChild; i++) {
//setting up pipes
pid_t childPID[i] = fork();

if(childPID[i] < 0) {
//close all pipes and quit
}else if (childPID[i] == 0) {
//redirect pipe
return 1;
//I'm expecting this to return when it try to execute "nonexist"
//but it didn't and keep running successed execl()
}else {
//close un-use pipes

while(true) {
for (int i = 0; i<numberOfChild; i++) {
//communicate with childs through pipe

for (int i = 0; i<numberOfChild; i++) {
//close reminded pipes
if (waitpid(childPID[i], NULL, 0) == -1){
return 1;
return 0;

This program still sent message to "nonexist" (but didn't receive anything back from it as expect).

Are there anyways to achieve my goal? Thank you!

Answer Source

You can arrange give the child one end of a pipe(), set to close-on-exec.

After the execl() fails (i.e. if the call returns), the child will write() to the pipe. If the parent receives anything on its end of the pipe (checking with poll() or similar), then it knows the child has failed.

If the message from the child contains an identifier of the child, then the pipe can be shared across all the children. Try to keep the write() small enough to be atomic, though!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download