How to start a process as running in background? - c

I've done a fork and and then an exec but I don't know how to start it in the background.
Should I use an argument after the exec? If so, which is it?

If you simply want to background a process use daemon().
If you want to spawn off a process that then backgrounds itself 1st use fork() and inside this 1st child call fork() again letting the 2nd child call exec*() for the process to be backgrounded. Let the initial parent wait() for the 1st child.
As the parent of the second child (the process fork()ed 1st) dies, the exec*()ed process will be reaped by init.
Note: The pattern above is sometimes referred to as "double-forking". See also here: Why fork() twice (and links from there)
Another interesting set of answers on this is here: Linux: Difference between forking twice and daemon(ise)

Related

How can I check when a Linux process and ALL its children exited?

I write a program in C. I do fork() in the main process in order to do execve() in the forked child process to execute an unknown app (given by a user in the command line). I know a PID of the process of the executed app - it is returned by fork(), but this unknown app can possibly fork() many times and I do not know PIDs of all its children (they are grandchildren of the main parent process). How can I check in the main parent process WHEN its child process (it is the unknown app) and ALL children of the unknown app exit? (I do not know even how many children it can have and I do not know PIDs of these children).
This can be done by making your parent process a subreaper. A subreaper gets all children orphaned by its descendants, which would traditionally always go to init (process ID 1). The subreaper status needs to be enabled before forking the interesting child process. Once this is done, a waitpid() or similar call for any process will return the child process and all orphaned descendants until it returns error [ECHILD] when the entire tree is gone.
On Linux, this is enabled using prctl()'s PR_SET_CHILD_SUBREAPER option and on FreeBSD this is enabled using procctl() PROC_REAP_ACQUIRE command (see man pages for details).
On Linux you will be able to monitor only one child process individually this way, since the orphans do not remember from which original fork call they came. On FreeBSD, PROC_REAP_GETPIDS allows distinguishing individual subtrees, although this is less efficient if the tree contains many processes.
You can use waitpid(-1,NULL, WNOHANG) to tell if one child has exited. If you receive a positive number (a pid) then one child has exited. In your parent process you have a line that checks if the amount of child processes you have, here called x, is more than 0. if it is use this command to see if any child process has ended. If you have x items then when you add an item increment x and when one exits decrement x. When x, the amount of children you have, is zero all you children have been killed.

How to restrict child thread or a child process to restrict from forking in C

In C language,I have a child thread(using pthreads),
Is there any way to restrict this child, so that we can't call fork inside this thread?
If we write fork inside, program should not compile.
I can also have a child process instead of child thread, as long as it cannot fork further.
Basically how can I have a child process or child thread, which cannot fork a process any further.
You can always try to play games with pthread_atfork: http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_atfork.html
Basically, you can use pthread_atfork() to install a "child" callback which always calls exit(). This way, your threads may still fork, but the forked process will exit immediately, so no harm will be done (and only a minimal overhead incurred).
With processes it may be somewhat more complicated. Linux allows you to limit a number of processes per user (so called RLIMIT_NPROC when set with setrlimit()). When this limit is reached, no further forks are possible for a given user id. Thus, you can create a parent process with a CAP_SETUID capability and a dummy user, having the RLIMIT_NPROC set to 1. This way, you can fork from parent, change the child uid to that of the "limited" user you've created in advance and drop the CAP_SETUID capability. At this point, child will have no possible way to fork itself.

Does the C execv() function terminate the child proccess?

Heres a breakdown of my code.
I have a program that forks a child (and registers the child's pid in a file) and then does its own thing. The child becomes any program the programmer has dignified with argv. When the child is finished executing, it sends a signal (using SIGUSR1) back to the parent processes so the parent knows to remove the child from the file. The parent should stop a second, acknowledge the deleted entry by updating its table, and continue where it left off.
pid = fork();
switch(pid){
case -1:{
exit(1);
}
case 0 :{
(*table[numP-1]).pid = getpid(); //Global that stores pids
add(); //saves table into a text file
freeT(table); //Frees table
execv(argv[3], &argv[4]); //Executes new program with argv
printf("finished execution\n");
del(getpid()); //Erases pid from file
refreshReq(); //Sends SIGUSR1 to parent
return 0;
}
default:{
... //Does its own thing
}
}
The problem is that the after execv successfully starts and finishes (A printf statement before the return 0 lets me know), I do not see the rest of the commands in the switch statement being executed. I am wondering if the execv has like a ^C command in it which kills the child when it finishes and thus never finishes the rest of the commands. I looked into the man pages but did not find anything useful on the subject.
Thanks!
execv replaces the currently executing program with a different one. It doesn't restore the old program once that new program is done, hence it's documented "on success, execv does not return".
So, you should see your message "finished execution" if and only if execv fails.
execv replaces the current process with a new one. In order to spawn a new process, you can use e.g. system(), popen(), or a combination of fork() and exec()
Other people have already explained what execv and similar functions do, and why the next line of code is never executed. The logical next question is, so how should the parent detect that the child is done?
In the simple cases where the parent should do absolutely nothing while the child is running, just use system instead of fork and exec.
Or if the parent will do something else before the child exits, these are the key points:
When the child exits, the parent will get SIGCHLD. The default handler for SIGCHLD is ignore. If you want to catch that signal, install a handler before calling fork.
After a child has exited, the parent should call waitpid to clean up the child and find out what its exit status was.
The parent can also call wait or waitpid in a blocking mode to wait until a child exits.
The parent can also call waitpid in a non-blocking mode to find out whether the child has exited yet.
What did you expect to happen? This is what execv does. Please read the documentation which says:
The exec() family of functions replaces the current process image with a new process image.
Perhaps you were after system or something, to ask the environment to spawn a new process in addition to the current one. Or.. isn't that what you already achieved through fork? It's hard to see what you want to accomplish here.

c language problem

i have a c problem can any one help me . i wrote a code of process creation in c language , it uses pid & fork() call. the fork call is use for making child process now can any body tell me how to make parent process? i know that creating a child in process make the process parent automatically but i want to make a parent process right from the start so can any one tell me how to do this,
Secondly i just create the process i don't know how to use it i cant assign any work(computation) to it.so can any one tell me how to use the process for work?
Third one i want to give a name to my process how can i do it & how i can control their execution?
please if anyone can enlighten me than please help me to understand all this.
i shall be thank full for this forever
thanks in advance
The fork call creates a new process that is identical to the existing process except for a few minor differences such as its pid, parent pid. The original process carries on from exactly the same place and this is the parent process. Which means your question is basically meaningless. You don't create the parent process, the original process becomes the parent process once it creates a child process.
It's a bit like asking "I created a child by getting pregnant and giving birth, but how do I create the parents?" You are a parent automatically.
Back to computers...
When you fork, the system call returns the pid of the child to the parent and 0 to the child, so you should have code something like:
int pid = fork();
if (pid == 0)
{
// in child, do child processing - normally exec an executable
}
else if (pid > 0)
{
// in parent, do some processing - often wait for child to complete
}
else
{
// fork failed - handle the error
}
When you fork a process, one process becomes two processes. Each continues running at exactly the same place. The only difference is that the fork returns the PID of the child process to the parent process and returns the value 0 to the child process.
Without any help, the child process does not know its parent. If the two processes need to communicate with one another then they will need to use some sort of IPC mechanism.
A common form of IPC is pipe. If one opens pipes before forking, then both the child and the parent keep the open file descriptors. This will allow both processes to communicate with one another. The parent is now free to communicate its PID to the child process if so desired.
Secondly i just create the process i don't know how to use it i cant assign any
work(computation) to it
You need to use fork and exec in pair make it run the program you want to execute.
Here is the wiki link for more information.
Fork-exec is a commonly used technique in Unix whereby an executing process spawns a new program. fork() is the name of the system call that the parent process uses to "divide" itself ("fork") into two identical processes. After calling fork(), the created child process is actually an exact copy of the parent - which would probably be of limited use - so it replaces itself with another process using the system call exec().
To create a parent process, take your code for creating a child and reverse the roles of parent and child. Presto change-o, the new process is the parent and the old process is the child.
For communications between the processes, use a pipe(2), or several. Also, there is shared memory.
To control execution, use kill(2) and wait(2). I'm not sure about assigning names, we might need to know what platform you're on.
About renaming (I assume you mean the name displayed by ps), to "rename" a process, just copy your new name into argv[0]

Can we start a background process using exec() giving & as an argument?

If not, how can we start a background process in C?
In Unix, exec() is only part of the story.
exec() is used to start a new binary within the current process. That means that the binary that is currently running in the current process will no longer be running.
So, before you call exec(), you want to call fork() to create a new process so your current binary can continue running.
Normally, to have the current binary wait for the new process to exit, you call one of the wait*() family. That function will put the current process to sleep until the process you are waiting is done.
So in order to create a "background" process, your current process should just skip the call to wait.
Use the fork() call to create a new process, then exec() to load a program into that process. See the man pages (man 2 fork, man 2 exec) for more information, too.
Fork returns the PID of the child, so the common idiom is:
if(fork() == 0)
// I'm the child
exec(...)

Resources