Difference between creating new process and child process in C (Windows) - c

I would like to create a new process of an exe from within the code itself, so that I can have two parallel processes.
But, I would like to them to be separate processes and not parent-child.
Is there a way to do this in C (Windows)?

In Windows, processes don't have parents. Some tools read the InheritedFromUniqueProcessId value, but this does not tell you which process started your process. It only tells you where handles and other attributes were inherited from. In practice however, this value is usually set to the ID of the process that started the child process.
On Vista and above, you can change the InheritedFromUniqueProcessId value by calling CreateProcess with the STARTUPINFOEX structure filled in appropriately: create an attribute list with InitializeProcThreadAttributeList, and add a
PROC_THREAD_ATTRIBUTE_PARENT_PROCESS attribute with UpdateProcThreadAttribute.
On XP, there is no official way of doing this. You can try to use NtCreateProcess or RtlCreateUserProcess, but these don't set up the Win32 subsystem properly so your program might not run.

An ugly way I've done it in the past is to launch a child process, which then launches a second child process, and then the first child exits. This causes the second child to lose any association with the original parent.
I'm sure I later found a better way to do this, but I've gone looking around and can't find anything at the moment.

The "easy" way is to use an intermediate command, see KB here:
http://support.microsoft.com/kb/315939
Another way to have independent processes is to ensure to do not inherit handles to ensure that the 2nd process, and creating a new process group. See Creating independent process!

Most likely forking a new process doesn't exist in windows rather you could use CreateProcess function to do that which is much easier and better option for windows.

Related

Linux C code to start another process asynchronously

I am looking for C code to use on a Linux based system to start another process asynchronously. The second process should continue, even if the first ends. I've looked through the "fork" and "system" and "exec" options, but don't see anything that will spawn a peer process that's not communicating with or a child of the original process.
Can this be done?
Certainly you can. In the parent fork() a child, and in that child first call daemon() (which is an easy way to avoid setsid etc.), then call something from the exec family.
In Linux (and Unix), every process is created by an existing process. You may be able to create a process using fork and then, kill the parent process. This way, the child will be an orphan but still, it gets adopted by init. If you want to create a process that is not inherited by another, I am afraid that may not be possible.
You do a fork (man 2 fork) followed by an execl (man 2 execl)
For creates a new process of the same image as the calling process (so a perfect twin), where execl replaces one of the twins with a new image.
If you search google for "fork execl" you will find many text book examples -- including how to use correctly fork() and exec()
The most common fork-execl you will still have the new process associated to the terminal -- to create a perfect background process you need to create what is called a daemon process -- the template for that can be fornd in this answer here Creating a daemon in Linux

How to continuously monitor process creation in Linux?

My process launches a process - let it be a shell in this example, but it's applicable to any process really. I need to get notified when the shell creates new processes and to obtain their PIDs.
I can take a snapshot of the whole process tree at any given time (well, pstree can), but how do I monitor creation of new processes by a process with a given PID?
So far I've found several ways to do so at How to monitor an external process for events by its PID in C? none of which really solve my problem:
Monitoring NetLink proc interfaces. Problem: requires root permissions which I do not have.
Custom library overriding the syscalls loaded into the shell process by LD_PRELOAD. Problem: it will be inherited by the children of the shell as well, and I do not want that - I only want to monitor the shell.
ptrace()ing the shell. Problem: flags that notify the parent (i.e. my process) about creating new processes, i.e. PTRACE_O_TRACEFORK, PTRACE_O_TRACEVFORK and PTRACE_O_TRACECLONE propagate ptrace()ing to child processes, and I only want to monitor the shell.
Making the shell cooperate. Problem: In BASH command callbacks (as used in undistract-me) are very hacky. I'd also prefer to avoid shell-specific code.
I feel like I'm missing something simple here. I feel like I could make one of the above solutions work with more hacks, but... surely I don't have to resort to the big guns like LD_PRELOAD and ptrace() for such a simple task, do I?
JFYI I'm coding this in Vala, but C snippets are welcome too.
No generic solution has been found so far so I had to resort to making the shell cooperate:
ZSH has pre-exec hook documented in
http://zsh.sourceforge.net/Doc/Release/Functions.html
KSH has a
debug hook documented in http://www.manpagez.com/man/1/ksh/
a hack that adds pre-exec to BASH can be found in
https://github.com/jml/undistract-me
I simply write callback commands into the relevant environment variables depending on the shell.

Is it possible to adopt a process?

Process A fork()s process B.
Process A dies and therefore init adopts B.
A watchdog creates process C.
Is it somehow possible for C to adopt B from init?
Update:
Or would it even be possible to have C adopt B directly (when A dies), if C were created prior to A's dead, without init becoming an intermediate parent of B?
Update-1:
Also I would appreciate any comments on why having the possiblity to adopt a process the way I described would be a bad thing or difficult to impossible to implement.
Update-2 - The use case (parent and children refer to process(es)):
I have an app using a parent to manage a whole bunch of children, which rely on the parent's managment facility. To do its job the parent relies on being notified by a child's termination, which is done via receiving the related SIGCHLD signal.
If the parent itself dies due some accident (including segfaulting) I need to restart the whole "family", as it's impossible now to trigger something on a child's termination (which also might due to a segfault).
In such a case I need to bring down all children and do a full system's restart.
A possible approach to avoid this situation, would be to have a spare-process in place which could take over the dead parent's role ... - if it could again receive the step children's SIGCHLD signals!
No, most definitely not possible. It couldn't be implemented either, without some nasty race conditions. The POSIX guys who make these APIs would never create something with an inherent race condition, so even if you're not bothered, your kernel's not getting it anytime soon.
One problem is that pids get reused (they're a scarce resource!), and you can't get a handle or lock on one either; it's just a number. So, say, somewhere in your code, you have a variable where you put the pid of the process you want to reparent. Then you call make_this_a_child_of_me(thepid). What would happen then? In the meantime, the other process might have exited and thepid changed to refer to some other process! Oops. There can't be a way to provide a make_this_a_child_of_me API without large restructuring of the way unix handles processes.
Note that the whole deal with waiting on child pids is precisely to prevent this problem: a zombie process still exists in the process table in order to prevent its pid being reused. The parent can then refer to its child by its pid, confident that the process isn't going to exit and have the child pid reused. If the child does exit, its pid is reserved until the parent catches SIGCHLD, or waits for it. Once the process is reaped, its pid is up for grabs immediately for other programs to start using when they fork, but the parent is guaranteed to already know about it.
Response to update: consider a more complicated scheme, where processes are reparented to their next ancestor. Clearly, this can't be done in every case, because you often want a way of disowning a child, to ensure that you avoid zombies. init fulfills that role very well. So, there has to some way for a process to specify that it intends to either adopt, or not, its grandchildren (or lower). The problem with this design is exactly the same as the first situation: you still get race conditions.
If it's done by pid again, then the grandparent exposes itself to a race condition: only the parent is able to reap a pid, so only the parent really knows which process a pid goes with. Because the grandparent can't reap, it can't be sure that the grandchild process hasn't changed from the one it intended to adopt (or disown, depending on how the hypothetical API would work). Remember, on a heavily-loaded machine, there's nothing stopping a process from being taken off the CPU for minutes, and a whole load could have changed in that time! Not ideal, but POSIX's got to account for it.
Finally, suppose then that this API doesn't work by pid, but just generally says, "send all grandchildren to me" or "send them to init". If it's called after the child processes are spawned, then you get race conditions just as before. If it's called before, then the whole thing's useless: you should be able to restructure your application a little bit to get the same behaviour. That is, if you know before you start spawning child processes who should be the parent of whom, why can't you just go ahead and create them the right way round in the first place? Pipes and IPC really are able to do all the required work.
No there is no way that you can enforce Reparenting in the way you have described.
I don't know of a good way to do this, but one reason for having it is that a process running can stand on its own or add a capability to a parent process. The adoption would occur as the result of an event, know by the (not yet) child, but not the parent. The soon-to-be child would send a signal to the parent. The parent would adopt (or not) the child. Once part of the parent, the parent/child process would be able to react to the event, whereas neither could react to the event when standing alone.
This docking behavior could be coded into the apps, but I don't know how to do it in real-time. There are other ways to achieve the same functionality. A parent, who could accept docking children could have its functionality extended in novel ways not previously known to the parent.
While the original question is tagged with unix, there is a way to achieve this on linux so it's worth mentioning. This is achievable with the use of a subreaper process. When a process's parent, it will get adopted by the nearest subreaper ancestor or init. So in your case you'll have process C set as subreaper via prctl(PR_SET_CHILD_SUBREAPER) and spawns process A, when process A dies, process B will be adopted by C
An alternative on Linux would be to spawn C in a separate PID namespace, making it the init process of the PID namespace and hence can adopt the children of A when A dies.

Process tree, how to find if a said process is the root one?

I have a directory monitoring application which works recursively by launching new processes.
I'd like to know if I'm the "root" process in this tree. I thought about trying to get the name of the caller process and check if it's the same as argv[0].
Is there a smarter way of doing this? Keep in mind, this is a Linux app.
Keep in mind, I don't have much time for this and I'm but a student, so a simple solution would be great.
Thanks for your time.
If you use fork() to create new processes, you can have a local variable initially set at zero that each child sets to 1 immediately after forking. Only the root process would still have it set at zero after a fork.
You could even increase it after each fork, which would let you know how deep in your process tree each process is.
EDIT:
If you cannot use this (e.g. because you do an exec() after fork), you can use any of the common ways that shells use to pass information to the programs that you launch:
Environment variables: call setenv() after fork() but before exec() - or add it in the environment when calling exec().
Use a special command line argument.
Use a special value for argv[0] when doing exec().
Have you the possibility to add an argument meaning "I'm not the root"? That seems the simplest approach.
If you are calling exec, add a special argument, or environment variable called "I_AM_NOT_THE_ROOT" which the child processes get, but the parent does not.
I recently used a command-line argument for this, but env variables might be more convenient.

Usage of Mutex across processes

OS: Windows Language: C/C++
The design demands to use a mutex variable across process and its sub processes.
If I create mutex in one process, I have to open the mutex in another processs to check the critical section's availablity.
To open the mutex, I need to know the name of the mutex created in parent process. Suppose, If I keep the mutex as my application name. I could know the name of the mutex, as it is fixed. However, If I load the second instance of my application parallel, there would be a confusion.
Can the following be the better idea?
I have an idea to name the mutex in the parent process as the process id. So now I need to fetch the Parent's process ID from the child process/grand child process to open the mutex.
I guess there are no direct ways to fetch parent process id from the grand child process. So I have to pass on the process id in every create process api(in lpenvironment parm).
Can anyone suggest a simple method, as mutexes are most commonly used.... I am a newbie.
The main idea is fine, but you can maybe make some implementation tweaks.
For one, if your application involves multiple processes cooperating, then the main "controller" process which spawns sub-processes can easily pass its PID via a command line argument. If sub-processes spawn their own children as well, they can transfer the PID via the same mechanism.
Taking this idea further, you can also skip the PID entirely and pass the mutex name itself via command line argument to child processes. This approach has the advantage that the parent and child processes do not need to both include code that derives the mutex name from the PID. By passing the mutex name itself you decouple child processes from having to know how it is produced. This approach is used by many mainstream apps, e.g. Google Chrome.
And finally, you can maybe do better by adding a random string (a GUID maybe?) to the mutex name. I don't believe anyone will name their own global synchronization object with the same name, but some extra precautions won't hurt.
As I understand it, you propose to use a process ID (PID) as the basis for naming a mutex to be used by your application and its subprocesses. This way, they will have their own mutex name that will not clash with the mutex name used by a second instance of your application.
This appears valid, but handles would be reliable than PIDs, because PIDs can get recycled. The method of using handles (passing them to child processes, similar to what you sugggest) is discussed on this StackOverflow thread.
I think passing the information you need to share to child processes is the way to go. Windows has the concepts for progress groups for a console process and its child processes, but this is really designed for being able to signal all the processes as a group -- not for sharing information among the group.
And there are also job objects for managing a group of processes that belong to a common job, but again, this is designed for managing a group of processes, not for information sharing between the processes in the group.
If I interprete the wording "a process and its sub-processes" as well as "child/grandchild", the situation is that you have a single parent process that launches one or several children (or, children launching grandchildren). Or, any combination of these, but either way, every process we talk about using the same mutex that is created by the parent.
If that assumption is correct, why not just use something embarrassingly simple as:
#define MUTEXNAME "MzdhYTYzYzc3Mzk4ZDk1NDQ3MzI2MmUxYTAwNTdjMWU2MzJlZGE3Nw"
In case you wonder where this one came from, I generated it with this one-liner:
php -r "echo substr(base64_encode(sha1('some text')), 0, -2);"
Replace 'some text' with your name, the current date, or whatever random words are at your mind at this very moment. The chances that any other application on your system will ever have the same mutex name is practically zero.

Resources