Reputation: 3652
I have the following two simple programs:
bye.cc
#include <iostream>
int main()
{ std::cout << "Bye bye bye world" << std::endl; }
hello.cc
#include <cstdlib>
#include <unistd.h>
#include <sys/wait.h>
#include <iostream>
using namespace std;
int main()
{
int status;
cout << "Hello world" << endl;
int pid = fork();
if (pid != 0) {
cout << "I am parent - " << pid << endl;
// wait for child to finish up......
cout << "Waiting for child to finish" << endl;
wait(&status);
cout << "Child finished, status " << status << endl;
} else {
cout << "--- I am child - " << pid << endl; // **Note**
execl("bye", "");
cout << "--- I am sleeping" << endl;
sleep(3);
exit(11);
}
}
In hello.cc, if the line marked "Note" is enabled (not commented), I get the expected behavior, sleep(3) is not executed, and "bye" is executed, expected msg printed to console.
$ ./hello
Hello world
I am parent - 27318
Waiting for child to finish
--- I am child - 0
Bye bye bye world
Child finished, status 0
However, when the line marked "Note" is commented, "bye" is NOT executed, and sleep(3) is performed.
$ ./hello
Hello world
I am parent - 27350
Waiting for child to finish
--- I am sleeping
Child finished, status 2816
Can someone please help me understand what might be going on. What I found very odd, if I replace the "cout" with a printf(), then the sleep performed.
Thank you, Ahmed.
Upvotes: 1
Views: 353
Reputation: 16540
the exec family of functions, when successful, do not return. That is why you do not see the sleep comment when the execl() is executed.
Upvotes: 0
Reputation: 71525
According to the spec, the argument list to execl
must be terminated by a NULL pointer (i.e. (char *)0
, not ""
).
Changing the nearby code is just changing what happens to be on the stack when you invoke execl
. As written, the program's behavior is undefined.
P.S. Always check the return value of library routines for errors.
Upvotes: 1