C++ how to pass command line args between processes? - c++

I have a parent process that needs to send it is command line args to the its child? How I can do this? I mean from parent.cpp to child .cpp?
Thanks

POSIX (Linux) solution:
Use execvp(const char *file, char *const argv[]) to run a programme with arguments in place of the current programme. The argv[] that you pass as reference, follows the same logic than the argv[] parameter passing in main().
If you want to keep your current process running and launch the new programme in a distinct process, then you have first to fork(). The rough idea is something like:
pid_t pid = fork(); // creates a second process, an exact copy of the current one
if (pid==0) { // this is exectued in the child process
char **argv[3]{".\child","param1", NULL };
if (execvp(argv[0], argv)) // execvp() returns only if lauch failed
cout << "Couldn't run "<<argv[0]<<endl;
}
else { // this is executed in the parent process
if (pid==-1) //oops ! This can hapen as well :-/
cout << "Process launch failed";
else cout << "I launched process "<<pid<<endl;
}
Windows solution
The easiest windows alternative is to use the ms specific _spawnvp() or similar functions. It takes same arguments as the exec version, and the first parameters tells if you want to:
replace the calling process (as exec in posix)
create a new process and keep the calling one (as fork/exec combination above)
or even if you want to suspend the calling process until the child process finished.

If fork() is used, then the child process inherits from the parent process.
http://man7.org/linux/man-pages/man2/fork.2.html
If you mean just passing variables between instances of objects in memory, then you'd create variables for int argc and char * argv[] to pass along.

In parent. Use
system("child_application my arg list");
In child. Use
int main(int argc, char *argv[])
For easy parsing args try boost program_options library.
In unix system can use fork. Child process get all parent memory.

Related

Should we use exit or return in child process

Saying that I have used fork to create one child process. Here is an example:
pid_t pid=fork();
if (pid==0) /* child */
{
// do something
exit(0); // _exit, exit or return????
}
else /* parrent */
{
wait(nullptr);
return 0;
}
I've seen many examples of fork. Some of them used _exit to terminate the child process to avoid flush the I/O buffer, others used exit to terminate the child process. But non of them used return. As my understanding, _exit and exit won't call destructors automatically, so is it better to call return instead of exit in the child process? Or because all examples that I've ever seen are C, instead of C++, so they don't need to worry about destructors?
You can use either _exit or exit, but you shouldn't use return. When you fork a child, you retain the entire call stack as part of forking the child. So if you use return, you end up returning up all the way through your program, potentially continuing on and performing other tasks, which is almost certainly not what you want.
For example, if you have something like this snippet:
int get_value()
{
pid_t pid;
if (!(pid = fork())) {
int x = 0;
// do something with x.
exit(x);
}
else {
int status;
wait(&status);
return status;
}
}
int main()
{
int value = get_value();
switch (get_value()) {
case 0:
// call f
break;
case 255 << 8:
// call g
break;
}
}
you'll could end up calling f or g or doing other work with return, which is definitely not desired.
If you call _exit, functions that are registered with atexit are not called. This is the right thing to do in threaded environments. If you're not working in a threaded environment and you don't have any handlers registered with atexit, then they should be functionally equivalents.
If you want destructors in your child process to be called, put the child process code in its own function and let its variables be automatically destroyed when they go out of scope. exit will not destroy objects for you, which is good because usually you do not want to destroy objects created in the parent process in your child process.
You could use return if you are looking for an exit code of the child process, just to say the process ran and executed correctly/not. Same as you do with your main function in a program. Otherwise just use exit to stop the process from running any further.
fork will copy the whole process, its not equivalent to launching a thread with a new main function.
Returning will simply return from the current function and the execution of the child will continue in the enclosing function.
So in you snippet you have to terminate the child or it will "escape". You can do that by calling exit() or std::terminate(). No destructors are called in both cases. Don't mix two different languages.
If you really need to call the destructors in the child, throw an exception and catch it in main. That will unwind the stack correctly.
Exit command should be avoid to use in any case except from ending the execution of the programme. For anything else, I would use return.

Running two programs concurrently

I have two C++ programs built in Ubuntu, and I want to run them concurrently. I do not want to combine them into one C++ project and run each on a different thread, as this is causing me all sorts of problems.
The solution I effectively want to emulate, is when I open two tabs in the terminal, and run each program in a separate tab. However, I also want one program (let's call this Program A) to be able to quit and rerun the other program (Program B). This cannot be achieved just in the terminal.
So what I want to do is to write some C++ code in Program A, which can run and quit Program B at any point. Both programs must run concurrently, so that Program A doesn't have to wait until Program B returns before continuing on with Program A.
Any ideas? Thanks!
In Linux you can fork the current process, which creates a new process.
Then you have to launch the new process with some exec system call.
Refer to:
http://man7.org/linux/man-pages/man2/execve.2.html
For example:
#include <unistd.h> /* for fork */
#include <sys/types.h> /* for pid_t */
#include <sys/wait.h> /* for wait */
int main(int argc,char** argv)
{
pid_t pid=fork();
if (pid==0)
{
execv("/bin/echo",argv);
}
}
You have multiple options here:
The traditional POSIX fork / exec (there are literally tons of examples on how to do this in SO, for example this one).
If you can use Boost then Boost process is an option.
If you can use Qt then QProcess is an option.
Boost and Qt also provide nice means manipulating the standard input/output of the child process if this is important. If not the classical POSIX means should do fine.
Take a look at the Linux operating system calls, fork() and exec(). The fork() call will create two copies of the current process which continue to execute simultaneously.
In the parent process, fork()'s return value is the PID (process ID) of
the child process.
In the child process, fork()'s return value is 0.
On error, fork()'s return value is -1.
You can use this to your advantage to control the behavior of the parent and child. As an example:
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
int main(int argc,char** argv)
{
char* progB = "/bin/progB";
char* args[progName, "arg1", "arg2", ..., NULL];
char* env[NULL]; // can fill in environment here.
pid_t pid=fork();
if (pid==0)
{
// In child...
execv(progB, args, env);
}
else if (pid == -1)
{
// handle error...
}
else
{
// In parent; pid is the child process.
// can wait for child or kill child here.
}
}
To wait until your child exits (in the third case above), you can use wait(2), which returns your child pid on successful termination or -1 on error:
pid_t result = waitpid(pid, &status, options);
To kill your child preemptively, you can send a kill signal as described in kill(2):
int result = kill(pid, SIGKILL); // or whatever signal you wish
This should allow you to manage your processes as described in the original question.

C++ - fork() and its return value

I'm having troubles with this simple exercise. Here is the code:
int main(int argc, char** argv) {
pid_t pid1,pid2,pid3;
int a=5,b=4,c=3,retval,retval2;
pid1=fork();
if(pid1==0){
pid3=fork();
if(pid3==0)
exit(a);
else if(pid3>0){
waitpid(pid2,&retval2,0);
cout<<WEXITSTATUS(retval2);
}
}
else if(pid1>0){
pid2=fork();
if(pid2==0){
cout<<"CIAO";
exit(b);
}
else if(pid2>0){
waitpid(pid3,&retval,0);
cout<<WEXITSTATUS(retval);
}
}
return 0; }
As you can see it's not that complicated. All I want to do is pid2(father) to print pid3(son) return value and pid3(father) to print pid2(son) return value. Any advice? I would appreciate it very much.
Because of the first fork (the one that sets pid1), the second forks run in different processes. In the pid1==0 branch, pid2 never gets a value, because that process never assigns it one. Likewise, in the pid1>0 branch, pid3 never gets a value.
It looks like you're expecting the two processes to share the same set of variables, but it doesn't work like that. Forking creates two independent processes, each with its own copy of all its variables.
In your program, pid1 and pid3 are children of the original process (let's call it pid0), pid2 is the child of pid1.
Variables pid1, pid2 etc are only updated in specific processes, and left unitialized in the others. Waiting for pid3 in any other process than pid0 for instance does not make sense, because other processes won't have pid3 correctly set. Furthermore, waiting for a process which isn't a child of the current process doesn't work.
Also, the wait syscall takes a pointer as its parameter for the terminated child process return value. Doing a wait(pid2) is incorrect.
Now, to get the result you want, you'll have to set some kind of communication channel between pid1 and pid0, so that they may transmit to each other the return code of their respective child. A pipe created in pid0 might do the trick.
System call references:
wait
pipe

How to create a process in C++ under Linux?

I'd like to create a process by calling a executable, just as popen would allow. But I don't want to actually communicate through a pipe with it: I want to control it, like sending signals there or find out if the process is running, wait for it to finish after sending SIGINT and so on, just like multiprocessing in Python works. Like this:
pid_t A = create_process('foo');
pid_t B = create_process('bar');
join(B); // wait for B to return
send_signal(A, SIGINT);
What's the proper way to go?
Use case for example:
monitoring a bunch of processes (like restarting them when they crash)
UPDATE
I see in which direction the answers are going: fork(). Then I'd like to modify my use case: I'd like to create a class which takes a string in the constructor and is specified as follows: When an object is instantiated, a (sub)process is started (and controlled by the instance of the class), when the destructor is called, the process gets the terminate signal and the destructor returns as soon as the process returned.
Use case now: In a boost state chart, start a process when a state is entered, and send termination when the state has been left. I guess, http://www.highscore.de/boost/process/process/tutorials.html#process.tutorials.start_child is the thing that comes closest to what I'm looking for, excpet that it seems outdated.
Isn't that possible in a non-invasive way? Maybe I have a fundamental misunderstanding and there is a better way to do this kind of work, if so I'd be glad to get some hints.
UPDATE 2
Thanks to the answers below, I think I got the idea a little bit. I thought, this example would print "This is main" three times, once for the "parent", and once for each fork() – but that's wrong. So: Thank you for the patient answers!
#include <iostream>
#include <string>
#include <unistd.h>
struct myclass
{
pid_t the_pid;
myclass(std::string the_call)
{
the_pid = fork();
if(the_pid == 0)
{
execl(the_call.c_str(), NULL);
}
}
};
int main( int argc, char** argv )
{
std::cout << "This is main" << std::endl;
myclass("trivial_process");
myclass("trivial_process");
}
The below is not a realistic code at all, but it gives you some idea.
pid_t pid = fork()
if (pid == 0) {
// this is child process
execl("foo", "foo", NULL);
}
// continue your code in the main process.
Using the previously posted code, try this:
#include <signal.h>
#include <unistd.h>
class MyProc
{
public:
MyProc( const std::string& cmd)
{
m_pid = fork()
if (pid == 0) {
execl(cmd.c_str(), cmd.c_str(), NULL);
}
}
~MyProc()
{
// Just for the case, we have 0, we do not want to kill ourself
if( m_pid > 0 )
{
kill(m_pid, SIGKILL);
wait(m_pid);
}
}
private:
pid_t m_pid;
}
The downside I see on this example will be, you can not be sure, the process has finished (and probably he will not) if the signal is emitted, since the OS will continue after the kill immediately and the other process may get it delayed.
To ensure this, you may use ps ... with a grep to the pid, this should work then.
Edit: I have added the wait, which cames up in a comment up there!
Have a look to fork() (man 2 fork)

Calling a function when thread is exiting in PThreads or Windows

I am creating a C++ library for both Linux (with PThreads) and Windows (with their built-in WinThreads) which can be attached to any program, and needs to have a function called when the thread is exiting, similar to how atexit works for processes.
I know of pthread_cleanup_push and pthread_cleanup_pop for pthreads, but these do not work for me since they are macros that add another lexical scope, whereas I want to declare this function the first time my library is called into, and then allow the program itself to run its own code however it needs to. I haven't found anything similar in Windows whatsoever.
Note that this doesn't mean I want an outside thread to be alerted when the thread stops, or even that I can change the way the thread will be exited, since that is controlled by the program itself, my library is just attached, along for the ride.
So the question is: What is the best way, in this instance, for me to have a function I've written called when the thread closes, in either Windows or Linux, when I have no control over how the thread is created or destroyed?
For example in main program:
void* threadFunc(void* arg)
{
printf("Hello world!\n");
return NULL;
}
int main(int argc, char** argv)
{
int numThreads = 1;
pid_t* pids = NULL;
pids = (pid_t*) calloc(sizeof(pid_t), numThreads);
pthread_create(&ntid, NULL, threadFunc, &nVal);
pthreads[0] = ntid;
pthread_join(pthreads[0], NULL);
return 0;
}
In library:
void callMeOnExit()
{
printf("Exiting Thread!\n");
}
I would want for callMeOnExit to be called when the thread reaches return NULL; in this case, as well as when the main thread reaches the return 0;. Wrapping pthread_exit would work for other cases, and could be a solution, but I'd like a better one if possible.
If anyone has any ideas on how I might be able to do this, that would be great!
So after a few code reviews, we were able to find a much more elegant way to do this in Linux, which matches both what Windows does with Fibers (as Neeraj points out) as well as what I expected to find when I started looking into this issue.
The key is that pthread_key_create takes in, as the second argument, a pointer to a destructor, which is called when any thread which has initialized this TLS data dies. I was already using TLS elsewhere per thread, but a simple store into TLS would get you this feature as well to ensure it was called.
Change this:
pthread_create(&ntid, NULL, threadFunc, &nVal);
into:
struct exitInformData
{
void* (CB*)(void*);
void* data;
exitInformData(void* (cp*)(void*), void* dp): CB(cp) data(dp) {}
};
pthread_create(&ntid, NULL, exitInform, new exitInformData(&threadFunc, &nVal));
Then Add:
void* exitInform(void* data)
{
exitInformData* ei = reinterpret_cast<exitInformData*>(data);
void* r = (ei.CB)(ei.data); // Calls the function you want.
callMeOnExit(); // Calls the exit notification.
delete ei;
return r;
}
For Windows, you could try Fls Callbacks. They FLS system can be used to allocate per thread (ignore the 'fiber' part, each thread contains one fiber) storage. You get this callback to free the storage, but can do other things in the callback as well.
I found out that this has already been asked, although the solution given then may not be the same as what you want...
Another idea might be to simply extend from the pthread_t class/struct, and override the pthread_exit call to call another function as you want it to, then call the superclass pthread_exit