1

If i run this code in xcode ,sleep return when child process exit in just 1 second;but when i make and run this code in terminal,it will sleep 10 seconds;why??

int main(int argc, const char * argv[])
{
  pid_t pid;
  if ((pid = fork()) ==0) {
      sleep(1);
  }else{
      sleep(10);
      printf("hello");
  }
 return 0;
}
u2takey
  • 13
  • 3

2 Answers2

0

Well if you checked the return code from sleep you would see it returning -1 and setting errno to EINTR.

Please see answer I posted for working around the issue if you need to use something akin to sleep.

Community
  • 1
  • 1
Anya Shenanigans
  • 91,618
  • 3
  • 107
  • 122
  • My really question is:my same code run in xcode and in terminal show different result.Why?I guess some setting in xcode cause this , but i wonder what is it. – u2takey Jul 29 '14 at 14:46
  • There's interference because of the debugger. You have to use the `while (nanosleep(...))` trick instead. It's a Mac behaviour that you have to work around if you're putting a sleep into your process early in the startup process. You'll see the same behaviour if you simply run the program under `lldb` at the command line – Anya Shenanigans Jul 29 '14 at 15:18
0

The function sleep will sleep for the desired amount of seconds or until a signal is being sent to the process. (man sleep)

In this case the signal SIG_CHLD is being sent to your program. SIG_CHLD is the signal that represents the termination of a child process.

To ignore the signal simply add:

signal(SIGCHLD, SIG_IGN);

and dont forget to include #include<signal.h>

Adding this line made the program execute correctly on my Mac.

For a more elaborate answer see this post: https://stackoverflow.com/a/7171836/947321

Community
  • 1
  • 1
0xfee1dead
  • 116
  • 1
  • 8
  • you haven't understand my question and your code not work in my xcode. 1. SIGCHLD default setting is SIG_IGN ,you do not need signal(SIGCHLD, SIG_IGN) ;2. even you set signal(SIGCHLD, SIG_IGN) my code in xcode still not work.My really question is:my same code run in xcode and in terminal show different result.Why?I guess some setting in xcode cause this , but i wonder what is it. – u2takey Jul 29 '14 at 14:44
  • I am using Xcode Version 5.1.1 (5B1008) and http://pastebin.com/9J0wUBBw works like a charm. And the different behaviour should be caused by the attached debugger, I am not certain though. – 0xfee1dead Jul 29 '14 at 16:32