I have picked the following example from APUE :
void daemonize(const char* cmd)
{
int i,fd0,fd1,fd2;
pid_t pid;
struct rlimit r1;
struct sigaction sa;
//clear all file masks
umask(0);
//get max number of file descriptors
if(getrlimit(RLIMIT_NOFILE,&r1) < 0)
{
perror("error getting file descriptor size");
return;
}
//become a session leader
if((pid = fork()) < 0)
{
perror("error forking");
return;
}
else if(pid == 0)
{
setsid();
}
else
{
exit(0); //parent exits
}
sa.sa_handler = SIG_IGN;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
if(sigaction(SIGHUP,&sa,NULL) < 0)
{
return;
}
if((pid = fork()) < 0)
{
return;
}
else if(pid != 0)
{
exit(0); //parent
}
//child continues
syslog(LOG_ERR,"chile continuing with pid : %d",getpid());
//change the working directory
if(chdir("/") < 0)
{
return;
}
if(r1.rlim_max == RLIM_INFINITY)
r1.rlim_max = 1024;
for(i=0;i<r1.rlim_max;i++)
close(i);
//attach the file descriptors to /dev/null
fd0 = open("/dev/null",O_RDWR);
fd1 = dup(0);
fd2 = dup(0);
//initialize the log file
openlog(cmd, LOG_CONS,LOG_DAEMON);
if(fd0!=0 || fd1!=1 || fd2!=2)
{
syslog(LOG_ERR,"unexpected file descriptors %d %d %d\n",fd0,fd1,fd2);
exit(1);
}
}
int main()
{
daemonize("date");
pause(); //how is this working???
}
What I don't understand is how the pause() from the main function is working? What I was expecting is that since we have done exit(0) for the parent process in daemonize(), it should have exited and resulted in the normal termination of the main() process. It should have never returned to the main() and the call to pause() should not even happen. Why it did not terminate and why the pause() got called?
The code forks twice, producing a parent, a child, and a grandchild. The first two each exit(0); the last returns from daemonize.
Related
I've included code that creates a series of child processes to divide the work for a task. There's a random chance for it to terminate (handled by the word_count function from which it calls abort()) and on this event, it should create a new child process to replace it. However, the program is being blocked on the read. I know this code is messy, but I want understand the problem before cleaning it up.
int pipes[nChildProc][2]; //pipe fd[0] is read end, fd[1] is write end
long child_f_size = fsize / nChildProc;
pid_t pids[nChildProc];
//start dividing the work among child processes
for(int i = 0; i < nChildProc; ++i) {
//srand(time(NULL));
//int crash = ((rand() / RAND_MAX + 1.0) < crashRate) ? 1 : 0;
if(pipe(pipes[i]) != 0) {
printf("Failed to create pipe.\n");
exit(1);
}
pid_t pid = fork();
FILE *child_fp;
pids[i] = pid;
if(pid < 0) {
printf("Failed to create child process.\n");
exit(1);
}
else if(pid == 0) { //child process
count_t temp_count = readFromFile(child_fp, fsize, child_f_size, char* name, int i, int nChildProc);
//IPC with the main process
if(write(pipes[i][1], &temp_count, sizeof(temp_count)) == -1)
printf("failed to write to pipe.\n");
close(pipes[i][1]);
close(pipes[i][0]);
exit(0); //deallocate process' memory space
}
}
//wait for a children to finish
int ret, status, i = 0;
while(wait(NULL) != -1) { // while there are children to wait on
ret = waitpid(pids[i], &status, WUNTRACED);
if(ret == -1) {
continue;
}
if(ret != 0) {// didn't exit normally
if(pipe(pipes[i]) != 0) {
printf("Failed to create pipe.\n");
exit(1);
}
pid_t pid = fork();
FILE *child_fp;
pids[i] = pid;
if(pid < 0) {
printf("Failed to create child process.\n");
exit(1);
}
else if(pid == 0) { //child process
count_t temp_count = readFromFile(child_fp, fsize, child_f_size, char* name, int i, int nChildProc);
//IPC with the main process
if(write(pipes[i][1], &temp_count, sizeof(temp_count)) == -1)
printf("failed to write to pipe.\n");
close(pipes[i][1]);
close(pipes[i][0]);
exit(0); //deallocate process' memory space
}
}
i = (i + 1) % nChildProc;//loop back to detect more processes that were terminated
}
long bytes;
count_t temp;
temp.linecount = 0;
temp.wordcount = 0;
temp.charcount = 0;
//add up all the values from children to count
printf("time to read.\n");
for(unsigned int j = 0; j < nChildProc; ++j) {
if((bytes = read(pipes[j][0], &temp, sizeof(temp))) < 0) {//blocked here
printf("Failed to read from pipe {%d}.\n", j);
exit(1);
}
if(bytes != 0) {
count.linecount += temp.linecount;
count.wordcount += temp.wordcount;
count.charcount += temp.charcount;
}
close(pipes[j][1]);
close(pipes[j][0]);
}
A couple of issues jump out:
if(ret != 0) {// didn't exit normally you've confused ret (which is the pid) for status (which is the exit code of the child)
You can't call wait on a process twice, since calling wait allows the system to release the resources associated with the process. You have several options on how to rewrite this code:
while(wait(NULL) != -1) { // while there are children to wait on
ret = waitpid(pids[i], &status, WUNTRACED);
One easy way is to use wait then lookup in the array which index it belongs to.
while((pid = wait(&status)) {
if (pid == -1) { // no children to wait on
break;
}
for(int i = 0; i < nChildProc; ++i) {
if (pid == pids[i]) break;
}
if (i >= nChildProc) {
unexpected_pid_do_something_smart();
}
// Leave the rest of the loop the same
Note: I didn't compile or test the above code.
I am working on a ncurses based file manager in C. The problem is that some child processes can take some time to complete and till that happens it remains stuck due to waitpid.
I can't use the WNOHANG flag because the next block of code is dependent on the output of the child process.
void getArchivePreview(char *filepath, int maxy, int maxx)
{
pid_t pid;
int fd;
int null_fd;
// Reallocate `temp_dir` and store path to preview file
char *preview_path = NULL;
allocSize = snprintf(NULL, 0, "%s/preview", cache_path);
preview_path = malloc(allocSize+1);
if(preview_path == NULL)
{
endwin();
printf("%s\n", "Couldn't allocate memory!");
exit(1);
}
snprintf(preview_path, allocSize+1, "%s/preview", cache_path);
// Create a child process to run "atool -lq filepath > ~/.cache/cfiles/preview"
pid = fork();
if( pid == 0 )
{
remove(preview_path);
fd = open(preview_path, O_CREAT | O_WRONLY, 0755);
null_fd = open("/dev/null", O_WRONLY);
// Redirect stdout
dup2(fd, 1);
// Redirect errors to /dev/null
dup2(null_fd, 2);
execlp("atool", "atool", "-lq", filepath, (char *)0);
exit(1);
}
else
{
int status;
waitpid(pid, &status, 0);
getTextPreview(preview_path, maxy, maxx);
free(preview_path);
}
}
In this case, I would like to carry forward with the rest of the program if the user decides to go to some other file. In what way can I change the architecture of the program?
If I have understood the question correctly then you want to unblock parent on either completion of child or any user input.
As suggested in this comment, you could handle SIGCHLD and one more signal say SIGUSR1. SIGUSR1 will be raised when you get user input. Following is the example where both SIGCHLD and 'SIGUSR1' is handled. If use inputs any number then it raises SIGUSR1 to parent and parent kill child. Else child will raise SIGCHLD on exit.
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
int raised_signal = -1;
static void cb_sig(int signal)
{
if (signal == SIGUSR1)
raised_signal = SIGUSR1;
else if (signal == SIGCHLD)
raised_signal = SIGCHLD;
}
int main()
{
int pid;
int i, a;
struct sigaction act;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
act.sa_handler = cb_sig;
if (sigaction(SIGUSR1, &act, NULL) == -1)
printf("unable to handle siguser1\n");
if (sigaction(SIGCHLD, &act, NULL) == -1)
printf("unable to handle sigchild\n");
pid = fork();
if (pid == 0) {
/* child */
for (i = 0; i < 10; i++) {
sleep(1);
printf("child is working\n");
}
exit(1);
} else {
/* parent */
if (-1 == scanf("%d", &a)) {
if (errno == EINTR)
printf("scanf interrupted by signal\n");
} else {
raise(SIGUSR1);
}
if (raised_signal == SIGUSR1) {
printf("user terminated\n");
kill(pid, SIGINT);
} else if (raised_signal == SIGCHLD) {
printf("child done working\n");
}
exit(1);
}
return 0;
}
I have a function in C which creates a child process and makes it run execvp.
int Execute(char **arg)
{
pid_t pid;
int status;
if ((pid=fork()) == 0)
{
execvp(arg[0],arg);
perror("Execvp error");
exit(1);
}
else if (pid > 0)
{
waitpid(pid, &status, 0);
}
else
{
perror("Fork error");
exit(2);
}
}
Now I want to alter the function to actually run execvp several times (for example 5), and make the parent process wait for all the children to finish. Tried wrapping it all in for loop, but execvp gets executed just once. I know that basically execvp 'replaces' the current program code, but have no idea whether the iteration does not go on.
Thank you for your help!
First, loop around the process creation collecting the child PIDs
pid_t pid[5];
int i;
for (i = 0; i < 5; i++) {
if ((pid[i]=fork()) == 0) {
execvp(arg[0],arg);
perror("Execvp error");
_exit(1);
}
if (pid[i] < 0) {
perror("Fork error");
}
}
Second, loop around the waitpid call for every valid PID.
for (i = 0; i < 5; i++) {
if (pid[i] > 0) {
int status;
waitpid(pid[i], &status, 0);
if (status > 0) {
// handle a process sent exit status error
}
} else {
// handle a proccess was not started
}
}
I'm writing a program that executes the word count command on the child process. The father process should send a sequence of lines entered by the user trough a pipeline to the child process.
I tried to do this but I ended up with an error.
This is my code:
int main ()
{
int fd[2];
char buff;
int pid;
int pip;
pid = fork();
pip = pipe(fd);
if (pid != 0)
{
pip = pipe(fd);
if (pipe == 0)
{
while (read(fd[0], &buff,1) > 0 )
{
write (fd[1],&buff,1);
}
close(fd[0]);
_exit(0);
}
}
else
{
dup2(fd[1],1);
close(fd[1]);
execlp ("wc","wc",NULL);
_exit(-1);
}
return 0;
}
I've also tried to use dup2 to associate the standard input from the child to the read descriptor of the pipe created by the father process.
But I get this error : wc: standard input: Input/output error.
How can I solve this?
UPDATED (the error is solved but I get an infinite loop)
int main ()
{
int fd[2];
char buff;
int pid;
int pip;
pip = pipe(fd);
if (pip == 0)
{
pid = fork();
if (pid != 0)
{
while (read(fd[0], &buff,1) > 0 )
{
write (fd[1],&buff,1);
}
close(fd[0]);
}
else {
dup2(fd[1],1);
close(fd[1]);
execlp ("wc","wc",NULL);
_exit(-1);
}
}
return 0;
}
#include <unistd.h>
int main ()
{
int fd[2];
char buff;
int pid;
int pip;
int status;
pip = pipe(fd);
if (pip == 0)
{
pid = fork();
if (pid != 0)
{
close(fd[0]);
while (read(0, &buff,1) > 0 )
{
write (fd[1],&buff,1); /* your old loop forwarded internally in the pipe only*/
}
close(fd[1]);
} else {
dup2(fd[0],0); /* you had dup2(fd[1], 1), replacing stdout of wc with the write end from wc */
close(fd[0]);
close(fd[1]);
execlp ("wc","wc",NULL);
_exit(-1);
}
}
wait(&status); /* reap the child process */
return 0;
}
I'm learning apue and I try to daemonize a process according to the code sample in apue. The code is as follows:
#include <syslog.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <signal.h>
#include <sys/resource.h>
int damonize(const char *cmd)
{
int i, fd0, fd1, fd2;
pid_t pid;
struct rlimit rl;
struct sigaction sa;
umask(0);
if(getrlimit(RLIMIT_NOFILE, &rl) < 0)
{
return 1;
}
if((pid = fork()) < 0)
{
return 2;
}
else if(pid != 0)
{
exit(0);
}
setsid();
sa.sa_handler = SIG_IGN;
sigemptyset(&sa.sa_mask);
sa.sa_flags = 0;
if(sigaction(SIGHUP, &sa, NULL) < 0)
{
return 3;
}
if((pid = fork()) < 0)
{
return 4;
}
else if(pid > 0)
{
exit(0);
}
if(chdir("/") < 0)
{
return 5;
}
if(rl.rlim_max == RLIM_INFINITY)
{
rl.rlim_max = 1024;
}
for(i = 0; i < rl.rlim_max; i++)
{
close(i);
}
fd0 = open("/dev/null", O_RDWR);
fd1 = dup(0);
fd2 = dup(0);
openlog(cmd, LOG_CONS, LOG_DAEMON);
if(fd0 != 0 || fd1 != 1 || fd2 != 2)
{
syslog(LOG_ERR, "unexpected file descriptors %d %d %d\n", fd0, fd1, fd2);
return 6;
}
}
int main(void)
{
FILE *fp;
int id;
fp = fopen("test.txt", "w+");
id = damonize("ls");
fprintf(fp, "%d", id);
fclose(fp);
exit(0);
}
I run the above program and use ps -axj, but there's no daemon process created by the program, and threre's no output in the file test.txt. My question is
What's wrong in my code? What causes the above two problems?
You won't see the daemonized process because it doesn't stick around. After it tries writing to the file, it exits.
But it won't write to the file, because your daemonize routine closes every file handle (and that's what fopen() uses under the hood). Try opening the file in main() after daemonize(), or in the loop closing all file descriptors, exclude the one associated with the file using fileno().
I am afraid that your program is oversophisticated (if such a word exists in English). You are spawning one child process, exit parents, then the child spawns another child and exits. The child of the child is then closing all possible (even not opened) file descriptors, then it opens "/dev/null" and redirect standard input, output and error there. The "daemonisation" is finished and your program tries to write some number into a file "fp" in the main function. However, this fp have been closed long time ago in daemonize.
In other words, the main problem is that your daemonize function is closing all possible file descriptors in the loop:
for(i = 0; i < rl.rlim_max; i++) close(i);
However, if you want to daemonize a process why not to start with a simple solution and once it works you can add features while keeping it working. For example if you start with:
int daemonize() {
pid_t pid;
pid = fork();
if (pid > 0) exit(EXIT_SUCCESS);
if (pid < 0) printf("Can't fork\n");
return(pid);
}
Then you can add code for closing standard input close(STDIN_FILENO); before return, and so on. After each modification test if it is still working.