Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

neowin

macrumors newbie
Original poster
Jun 27, 2011
19
0
I am trying to daemonize a process. I am calling the below mentioned function wen ever a flag is set. The thing is I am not able to terminate the process after my use. I tried pressing ctrl+c to no avail. I tried closing the terminal, bu the process still runs in the background. The only way i can stop the process from running was by restarting the system. Is there any way to terminate the process without restarting my system?

Code:
void Daemonize(){
    parent_id = fork();
    if(parent_id!=0){
        printf("Daemonized \n");
        exit(0);
    }
    setsid();
}
 
Last edited by a moderator:

mfram

Contributor
Jan 23, 2010
1,307
343
San Diego, CA USA
I am trying to daemonize a process. I am calling the below mentioned function wen ever a flag is set. The thing is I am not able to terminate the process after my use. I tried pressing ctrl+c to no avail.

The whole point of daemonize is to place your program in the background if you run it from a terminal. Isn't that what you are trying to accomplish?

Here is a sample program. In this program, if the daemonize call is there, the program returns immediately back to the prompt but the child process continues in the background writing to the file. If daemonize is not there the program will pause for 10 seconds as it writes to the file.

If you want to see the program running, issue a 'ps ux' command. You will see it running. You can kill it with 'kill <pid>' which you get from the ps command.

Code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

void daemonize(void)
{
        pid_t p = fork();

        if (p != 0)
        {
                // parent, exit now
                exit(0);
        }

        setsid();
}

main()
{
        FILE *fp;
        int i;

        daemonize();

        if ((fp = fopen("test.txt", "w")) == NULL)
        {
                exit(0);
        }

        for(i = 0; i < 10; i++)
        {
                fprintf(fp, "%d\n", i);
                sleep(1);
        }

        fclose(fp);
}

Code:
imac:~/Documents/fork-test> make ftest
cc     ftest.c   -o ftest
imac:~/Documents/fork-test> ./ftest
imac:~/Documents/fork-test> ps ux
USER     PID  %CPU %MEM      VSZ    RSS   TT  STAT STARTED      TIME COMMAND
rmoore   194   0.0  0.0  2456328   1256   ??  Ss   13Oct11   0:01.76 /sbin/launchd
rmoore  5730   0.0  0.0  2434784    196   ??  Ss   10:07PM   0:00.00 ./ftest
...
imac:~/Documents/fork-test> kill 5730
 

neowin

macrumors newbie
Original poster
Jun 27, 2011
19
0
thanks guys...Will go through the document... and for the "ps ux" command :)
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.