2

这是我的代码

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <syslog.h>
#include <string.h>
#include <iostream>

int main(int argc, char *argv[]) {
    pid_t pid, sid;
    int sec = 10;

    pid = fork();
    if (pid < 0) {
        perror("fork");
        exit(EXIT_FAILURE);
    }
    if (pid > 0) {
        std::cout << "Running with PID: " << pid << std::endl;      
        exit(EXIT_SUCCESS);
    }
    umask(0);        

    sid = setsid();
    if (sid < 0)
        exit(EXIT_FAILURE);

    if ((chdir("/")) < 0)
        exit(EXIT_FAILURE);    /* Log the failure */

    close(STDIN_FILENO);
    close(STDOUT_FILENO);
    close(STDERR_FILENO);

    while (1) {
        execl("/bin/notify-send", "notify-send", "-t", "3000", "Title", "body", NULL);
        sleep(sec); 
    }
    exit(EXIT_SUCCESS);
}

我希望它每 10 秒发出一次通知。守护程序运行正常,但未发出任何通知。

4

1 回答 1

1

execl不返回 - 它用一个新程序替换正在运行的程序。所以在循环中运行它sleep是没有意义的——它只会运行一次。

我认为你应该system改用。它执行命令并返回。

另一种方法是fork每次在循环中,让孩子做execl,而父母会继续循环。

于 2012-05-14T08:47:57.963 回答