Ubuntu-守护进程不创建文件
Ubuntu-Daemon does not create file
我正在尝试 运行 Ubuntu 18.04.2 LTS 上的一个简单守护进程,它应该将一些数据写入日志文件。父进程以退出代码 0 终止,但没有创建文件。
此外,当我在fork()
之后设置断点时,pid
例如是835。当我用 ps -p 835 -o comm=
查询这个程序的进程名称时,我得到 LinuxTest.out <defunct>
,但是当我让程序继续并再次查询进程名称时,没有显示输出,即使子进程应该是由于代码后面的无限循环,仍然 运行ning。
我正在使用 Visual Studio 2019 和 Remote Build。我还尝试通过 SSH 登录到服务器并在那里以 sudo 权限执行构建的程序,但也没有任何反应。
int main() {
pid_t pid, sid;
// Fork off the parent process
pid = fork();
// if we got a good PID, then we can exit the parent process
if(pid > 0) exit(EXIT_SUCCESS);
else exit(EXIT_FAILURE);
// create new SID for child process
sid = setsid();
if(sid < 0) exit(EXIT_FAILURE);
// change the current working directory
if(chdir("/") < 0) {
exit(EXIT_FAILURE);
}
// change the file mode mask
umask(0);
// close out the standard file descriptors
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
// Open a log file in write mode.
FILE* fp = fopen("Log.txt", "w+");
while(1) {
sleep(1);
fprintf(fp, "Logging info...\n");
fflush(fp);
}
fclose(fp);
}
为什么没有到达创建文件的点,为什么不让子进程保持活动状态?
你有:
if(pid > 0) exit(EXIT_SUCCESS);
else exit(EXIT_FAILURE);
当以更正统的样式格式化时,与:
if (pid > 0)
exit(EXIT_SUCCESS);
else
exit(EXIT_FAILURE);
如果fork()
成功,则父退出成功,子退出失败;如果 fork()
失败,父级以失败状态退出。
将其更改为:
if (pid > 0)
exit(EXIT_SUCCESS);
else if (pid < 0)
exit(EXIT_FAILURE);
/* Child is running here: pid == 0 */
我正在尝试 运行 Ubuntu 18.04.2 LTS 上的一个简单守护进程,它应该将一些数据写入日志文件。父进程以退出代码 0 终止,但没有创建文件。
此外,当我在fork()
之后设置断点时,pid
例如是835。当我用 ps -p 835 -o comm=
查询这个程序的进程名称时,我得到 LinuxTest.out <defunct>
,但是当我让程序继续并再次查询进程名称时,没有显示输出,即使子进程应该是由于代码后面的无限循环,仍然 运行ning。
我正在使用 Visual Studio 2019 和 Remote Build。我还尝试通过 SSH 登录到服务器并在那里以 sudo 权限执行构建的程序,但也没有任何反应。
int main() {
pid_t pid, sid;
// Fork off the parent process
pid = fork();
// if we got a good PID, then we can exit the parent process
if(pid > 0) exit(EXIT_SUCCESS);
else exit(EXIT_FAILURE);
// create new SID for child process
sid = setsid();
if(sid < 0) exit(EXIT_FAILURE);
// change the current working directory
if(chdir("/") < 0) {
exit(EXIT_FAILURE);
}
// change the file mode mask
umask(0);
// close out the standard file descriptors
close(STDIN_FILENO);
close(STDOUT_FILENO);
close(STDERR_FILENO);
// Open a log file in write mode.
FILE* fp = fopen("Log.txt", "w+");
while(1) {
sleep(1);
fprintf(fp, "Logging info...\n");
fflush(fp);
}
fclose(fp);
}
为什么没有到达创建文件的点,为什么不让子进程保持活动状态?
你有:
if(pid > 0) exit(EXIT_SUCCESS);
else exit(EXIT_FAILURE);
当以更正统的样式格式化时,与:
if (pid > 0)
exit(EXIT_SUCCESS);
else
exit(EXIT_FAILURE);
如果fork()
成功,则父退出成功,子退出失败;如果 fork()
失败,父级以失败状态退出。
将其更改为:
if (pid > 0)
exit(EXIT_SUCCESS);
else if (pid < 0)
exit(EXIT_FAILURE);
/* Child is running here: pid == 0 */