user3549736
user3549736

Reputation: 1

Problems fork() don't executes processes

I wrote a code that goes into infinite loop to do periodic checks on a three-phase meter. To send data to the server in json format, I use a program written ad-hoc deals to take the data and send them to the server. The problem is that this mechanism works for a few hours. After this time the fork stop to call the program used for sending data and the program goes on.

In your opinion what could be the problem?

Thanks in advance for your response

P.S. Below the code used for fork()

int pid = fork();

if ( pid == 0 ) {

    execlp("./json_send","./json_send",0);

} else {
    printf( "\nParent process: %d", pid );
}

Upvotes: 0

Views: 762

Answers (2)

user3549736
user3549736

Reputation: 1

I found the problem. When I call fork() without wait, fork creates many zombie processes. The solution is "double fork()". I found solution in this site:

http://thinkiii.blogspot.it/2009/12/double-fork-to-avoid-zombie-process.html

Upvotes: 0

Please read carefully fork(2) man page. fork -and execve and most other syscalls- can (and does sometimes) fail (e.g. because of limits: see setrlimit(2)...). So code at least:

fflush(NULL);
pid = fork();
if ( pid == 0 ) {
  execlp("./json_send","./json_send",NULL);
  perror("execlp json_send");
} else if (pid>0) {
  printf( "\nParent process: %d\n", pid );
}
else { /* fork failed */
  perror("fork");
  exit(EXIT_FAILURE);
}

BTW, you should always wait (using e.g. waitpid(2) ...) for your child processes, to avoid zombie processes.

Please read Advanced Linux Programming which has several chapters devoted to relevant subjects.

BTW, if json_send is your small program, I would consider incorporating its functionalities (and some of its code) inside your forking program. I would also consider using syslog(3) for logging purposes. You may need to code an event loop (see this answer) using poll(2) etc...

Also, compile your program with gcc -Wall -g, use the gdb debugger, and perhaps also strace

Upvotes: 3

Related Questions