

Ask HN: Please explain what happens in this execl() problem. - chanux

We were studying for the Unix System programming module. And a friend came up with this problem. I got the code, simplified and did several changes to it. Following is the code.<p>#include&#60;stdio.h&#62;
main()
{
   printf("Here comes the date");
   printf("Line number 3 before execl\n");
   printf("Line number 2 before execl");
   printf("Line number 1 before execl");
   execl("/bin/date", "date", 0);
   printf("Line number 1 after execl");
   printf("Line number 2 after execl\n");<p>exit (0);
}<p>Friend complained that execl() overlaps not only the code after it but the code before it. But found that execl() overlaps the code before it until it finds a line feed. Why this happen?. Please explain. (Yes, code looks lame &#38; I get two warnings for execl() &#38; exit() when compile)
======
cperciva
This had better not be a homework problem.

The lines "Line number 2 before execl" and "Line number 1 before execl" will
not be printed on most systems because most systems default to line-buffering
(when writing to a terminal) or fully buffering (otherwise) output.

The lines "... after execl" will not be printed if execl succeeds, because
execl does not return if it succeeds.

Other bugs: You're not checking the return status of execl; you've declared
main incorrectly; you need to #include <unistd.h> and <stdlib.h> if you're
going to use execl and exit; you should pass a terminating NULL to execl, not
0 (the C compiler will coerce 0 to a pointer, but NULL is not guaranteed to be
(void *)0).

~~~
parenthesis
I thought 'the' standard said that 0 used in pointer contexts is interpreted
by the compiler as a null pointer, even if the machine's representation of a
null pointer is not 0.

~~~
cperciva
I'm sure there is _a_ standard which says that... but the nice thing about
standards is that there are so many to choose from. :-)

It's not something which you should rely upon.

------
parenthesis
> I get two warnings for execl() & exit() when compile
    
    
      man execl
      man 3 exit
    

will tell you which headers you need to #include.

~~~
chanux
Thank you. I hope that is a good 'habit' on the way becoming a good sys
programmer, which I didn't think of (reading man for those things).

------
alecco
buffers?

BTW, don't think this is "Hacker News" ;)

~~~
chanux
If you mean my problem is not suitable here, I'm sorry. I know I had to ask in
stackoverflow, but when I got this problem I felt that HN sure has answer. But
now I realize this kind of problems will make HN a mess. I'll try to post the
best & appropriate here in future. I keep learning :) .

