C function to start process but to return right away


Login or Register for Dates, Times and to Reply

 
Thread Tools Search this Thread
Top Forums Programming C function to start process but to return right away
# 1  
C function to start process but to return right away

Hello,

I am using C on a Centos box with gcc as the compiler.

I want a function to do something, them make an http request to some server (most probably using curl but suggestions are welcome) and return right away without waiting for the server's answer on that request.

What should I use (library, function, design...) to achieve that?

Thank you
# 2  
fork and exec. fork() copies your process but returns a different value to the copy so it can take a new direction. exec() replaces it with a different program. the original program can do other things and/or wait for the child to complete. see man fork, man execv, man wait.

Code:
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(void)
{
  pid_t pid=fork();
  if(pid < 0)
  {
    perror("Couldn't fork");
    exit(1);
  }
  else if(pid == 0) // child code
  {
    execv("/bin/echo", "/bin/echo", "asdf", NULL);
    // this should never happen since execv REPLACES the process that calls it
    exit(1);
  }
  else // parent code
  {
    int status;
    // do other stuff.  child will keep running.
    sleep(5);

    // wait for child to complete
    wait(&status);
    printf("child returned %d\n", WEXITSTATUS(status));
    return(0);
  }
}

This User Gave Thanks to Corona688 For This Post:
# 3  
Thanks! I like the strategy. I am putting those codes inside a fastcgi program:

Code:
int main(void)
{
  initialize();
  while (FCGI_Accept() >= 0)  
  {
		  pid_t pid = fork();
		  if(pid < 0)
		  {
		    exit(1);
		  }
		  else if(pid == 0)
		  {
		    //do things
				  continue;
		  }
		  bstring s = bfromcstr("Content-type: text/html\n\n");

    bcatcstr(s, "hellow");
    printf("%s",s->data);
  }
  return EXIT_SUCCESS;
}

From initial testing, it works fine. Do you see any pitfalls though?

Thanks agains
# 4  
You're not calling wait() anywhere, so you may be generating lots of zombie processes -- processes that have completed but haven't been waited for.

You may wish to keep a thread around that does nothing but call wait() in a loop to handle them. You could also catch the SIGCHLD signal but this is subject to problems.[COLOR="#738fbf"]

Code:
int main(void)
{
  initialize();
  while (FCGI_Accept() >= 0)  
  {
		  pid_t pid = fork();
		  if(pid < 0)
		  {
		    exit(1);
		  }
		  else if(pid == 0)
		  {
		    //do things
				  continue;
		  }
		  bstring s = bfromcstr("Content-type: text/html\n\n");

    bcatcstr(s, "hellow");
    printf("%s",s->data);
  }
  return EXIT_SUCCESS;
}

You are not making your child processes quit! That continue should be an exit, unless you want growing swarms of copies of your process all waiting on while (FCGI_Accept() >= 0).
This User Gave Thanks to Corona688 For This Post:
# 5  
You'r right. 100% right. I should call exit(1) instead of continue. At that point, right after this exit, isn't the child process killed? If the child process is killed why would I need a way to handle zombies?
I don't want to wait for the child to return because I want to have the parent return as soon as possible.
# 6  
Quote:
Originally Posted by JCR
You'r right. 100% right. I should call exit(1) instead of continue. At that point, right after this exit, isn't the child process killed? If the child process is killed why would I need a way to handle zombies?
The process terminates, but isn't removed from the process table until you wait() for it. Things like runtime statistics and return value can still be gleaned from it until you do, which is why they keep it. You don't need to wait() for it at the bottom of your loop there(and thereby block until it quits) but something in your program must do it sooner or later.

Fortunately it's not a big deal. There's nonblocking ways to check if a child has exited ( see waitpid's WNOHANG flag ), ways to handle child exits asynchronously with sigaction and SIGCHLD(not reccomended; if you get two SIGCHLD's too fast to handle you might miss one), or you can just do a wait() loop in an independent thread. The thread method's probably the most bulletproof and least resource-intensive, the thread will spend 99.9% of its time asleep and only run when needed. (or when you want it to.)

I think you misunderstood a little with the exit(1). It doesn't have to be exit(1). In the example I showed I used execv(), which replaces the process with something else, so the exit(1) would only happen if execv() failed to load /bin/echo. If you're just doing your own thing you could have an exit(0) for normal return and exit(1) on error and so forth, it's just the return value for main().

---------- Post updated at 03:15 PM ---------- Previous update was at 02:58 PM ----------

It occurs to me to ask, how many loops does this program run? I figured it was like a daemon that takes several requests, which could create zombies forever which would be bad. If the loop only runs once and it quits thereafter, it's probably safe not to wait() if the child is disowned first. It will be owned by init instead and waited for by it. Researching how to do this.

Last edited by Corona688; 06-08-2010 at 07:07 PM..
This User Gave Thanks to Corona688 For This Post:
# 7  
It is a fastcgi program that interacts with a nginx webserver through a socket. I am using supervisord to spawn instances of this progam.
The number of loops could be infinite.
Login or Register for Dates, Times and to Reply

Previous Thread | Next Thread
Thread Tools Search this Thread
Search this Thread:
Advanced Search

Test Your Knowledge in Computers #105
Difficulty: Easy
The programming interface, file abstraction, built-in networking and persistent background processing are all features and capabilities supported by a Unix or Linux OS.
True or False?

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Function - Make your function return an exit status

Hi All, Good Day, seeking for your assistance on how to not perform my 2nd, 3rd,4th etc.. function if my 1st function is in else condition. #Body function1() { if then echo "exist" else echo "not exist" } #if not exist in function1 my all other function will not proceed.... (4 Replies)
Discussion started by: meister29
4 Replies

2. Shell Programming and Scripting

Return: can only `return' from a function or sourced script

Not sure where the problem is. I can run the script without any issue using the following command. . /opt/app/scripts/cdc_migration.sh But it fails with the below error when I try it this way /opt/app/scripts/cdc_migration.sh /opt/app/scripts/cdc_migration.sh: line 65: return: can only... (1 Reply)
Discussion started by: svajhala
1 Replies

3. Shell Programming and Scripting

Pass return value of a function in background process

Hi, I have created a function f1 defined in script A.sh .I have called this function in background . But I want to use its return value for another function f2 in script A.sh. I tried declaring it as a global variable, yet it always returns the status as 0. Is there any way with which I can get... (7 Replies)
Discussion started by: ashima jain
7 Replies

4. UNIX for Dummies Questions & Answers

Script to start background process and then kill process

What I need to learn is how to use a script that launches background processes, and then kills those processes as needed. The script successfully launches the script. But how do I check to see if the job exists before I kill it? I know my problem is mostly failure to understand parameter... (4 Replies)
Discussion started by: holocene
4 Replies

5. Shell Programming and Scripting

Return a value from called function to the calling function

I have two scripts. script1.sh looks -------------------------------- #!/bin/bash display() { echo "Welcome to Unix" } display ----------------------------- Script2.sh #!/bin/bash sh script1.sh //simply calling script1.sh ------------------------------ (1 Reply)
Discussion started by: mvictorvijayan
1 Replies

6. Shell Programming and Scripting

return in function

I am using ksh. I want to know how can we make any function to return string or double value. I dont want to use the global variables. (5 Replies)
Discussion started by: PRKS
5 Replies

7. Shell Programming and Scripting

return value of a function

I have write a shell function to get the maximum of a vector. However, the returned value from the function is not always the correct one. Here is the script: maxval() { local max j i size arrval size=$1 ; shift max=-999999999 i=0 while do arrval="$1" if then ... (5 Replies)
Discussion started by: fl0r10
5 Replies

8. Shell Programming and Scripting

Script - How to automatically start another process when the previous process ends?

Hi all, I'm doing automation task for my team and I just started to learn unix scripting so please shed some light on how to do this: 1) I have 2 sets of datafiles - datafile A and B. These datafiles must be loaded subsequently and cannot be loaded concurrently. 2) So I loaded datafile A... (10 Replies)
Discussion started by: luna_soleil
10 Replies

9. Shell Programming and Scripting

return value of a function

Hi I have a doubt in the way the variables inside a function are treated . if a function is called from the main script directly, the variables inside them act as global variables. however if the return value of the function is stored to some other variable in the main script as shown,... (3 Replies)
Discussion started by: prez
3 Replies

10. Shell Programming and Scripting

how to start a process and make it sleep for 5 mins and then kill that process

how to start a process and make it sleep for 5 mins and then kill that process (6 Replies)
Discussion started by: shrao
6 Replies

Featured Tech Videos