forked from 54shady/linuxc
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
97 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,49 @@ | ||
#include <stdio.h> | ||
#include <stdlib.h> | ||
#include <fcntl.h> | ||
|
||
/* | ||
* 创建一个daemon的核心 | ||
* 调用fork,父进程退出,子进程调用setsid | ||
*/ | ||
void daemonize(void) | ||
{ | ||
pid_t pid; | ||
|
||
/* | ||
* Became a session leader to lose controlling TTY | ||
*/ | ||
if (pid = fork() < 0) | ||
{ | ||
perror("fork"); | ||
exit(1); | ||
} | ||
else if (pid != 0) /* parent */ | ||
exit(0); | ||
|
||
/* Children call setsid */ | ||
setsid(); | ||
|
||
/* | ||
* Change the curren working directory to the root | ||
*/ | ||
if (chdir("/") < 0) | ||
{ | ||
perror("chdir"); | ||
exit(1); | ||
} | ||
|
||
/* | ||
* Attach file descriptors 0, 1, 2 to /dev/null | ||
*/ | ||
close(0); | ||
open("/dev/null", O_RDWR); | ||
dup2(0, 1); | ||
dup2(0, 2); | ||
} | ||
|
||
int main(int argc, char *argv[]) | ||
{ | ||
daemonize(); | ||
while (1); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
#include <stdio.h> | ||
#include <unistd.h> | ||
|
||
/* | ||
* 查看终端对应的设备文件名 | ||
* 在图形终端窗口下运行这个程序结果可能是/dev/pts/0 | ||
* 用 Ctrl-Alt-F1 切换到字符终端运行这个程序结果是/dev/tty1 | ||
*/ | ||
|
||
int main(int argc, char *argv[]) | ||
{ | ||
printf("fd 0 : %s\n", ttyname(0)); | ||
printf("fd 1 : %s\n", ttyname(1)); | ||
printf("fd 2 : %s\n", ttyname(2)); | ||
return 0; | ||
} |