Reputation: 23780
Here is my code:
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
pid_t pid;
pid = fork();
if (pid != 0)
{
exit(0);
}
setsid();
chdir("/");
while(1){
sleep(4);
printf("%s\n", "Hello world!");
}
return 0;
}
Ok now I will open the Terminal, and start bash inside again, and the output will be:
Last login: Tue Jun 2 14:29:49 on ttys000
Korays-MacBook-Pro:~ koraytugay$ bash
bash-3.2$ ./a.out
bash-3.2$ Hello world!
Hello world!
Hello world!
exit
exit
Korays-MacBook-Pro:~ koraytugay$ Hello world!
Hello world!
What I want to show here is that, I started terminal, which starts bash as far as I know, and inside the bash I started one more bash and started my program.
Even that I exited the bash, the deamon was still running, which is what I was expecting..
But the problem is, if I quit the Terminal application, and start it again, I will not see "Hello World" anymore..
All I see is:
Last login: Tue Jun 2 14:30:46 on ttys000
Korays-MacBook-Pro:~ koraytugay$
Is my deamon dead after I close the terminal? Why in the first situation, even that I exit bash, the parent bash still shows the Hello Worlds, but not after I re-start the Terminal?
This is what I mean by Terminal: http://blog.teamtreehouse.com/introduction-to-the-mac-os-x-command-line
Also I want to add this information,
In the new terminal when I execute
ps -A
I am still seeing:
41891 ?? 0:00.01 ./a.out
41902 ?? 0:00.01 ./a.out
However no text? Why is no text sent to standard out? The deamons still execute as far as I can tell, and the terminal is showing me the standard out, isn't it?
Upvotes: 0
Views: 152
Reputation: 4122
This is expected, due to the fact that when you quit the terminal file handler to which you application writes its output (stdout) is gone. When you start the terminal again it does not restore the same file handler. This is the same if your app is writing in a file and you have deleted it. If you create new file with same path it will not continue to write inside. If you want to keep the output, after the terminal is you have to write in a file, like log file from daemons like httpd, samba, sshd, etc.
Upvotes: 1
Reputation: 409166
If a terminal is closed, all processes who write to that TTY device will have their standard output closed. Opening a new terminal will not cause the close stdout
to be magically restored.
Upvotes: 1
Reputation: 61910
You have forked from the initial bash
instance which connects the stdin, stdout and stderr with a specific terminal. When you terminate the bash instance the terminal to which the stdin, stdout and stderr were connected will be closed, and therefore for your daemon writing to any of these descriptors is effectively writing to a descriptor linked to a removed file or device.
Upvotes: 3