Linux/OSX/Windows - Waiting end of process - linux

Under OSX, there is "open -W" which allows to wait the end of an executable.
What is the equivalent instruction for windows ?
Linux does have this non-blocking behaviour with programs like sublime-text (subl). How does it do that (execv ?)
Basically, I'm trying ,within a C program, to launch an executable and wait until it ends up.

With the edit, under linux, you're looking at:
childpid = fork();
if (childpid) {
execve("program", argvp, envp);
} else {
int status;
pid_t pid = wait(&status);
}
under windows, you need to use CreateProcess to create the process, and then use WaitForSingleObject to wait for the process to terminate; e.g.
PROCESS_INFORMATION processInformation = {0};
STARTUPINFO startupInfo = {0};
startupInfo.cb = sizeof(startupInfo);
bool status = CreateProcess(L"Program", L"args", 0, 0, 0,
NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW,
0, 0, &startupInfo, &processInformation);
if (status) {
WaitForSingleObject(processInformation.hProcess, INFINITE);
}

Under Linux, a parent process can wait for a child process to terminate by using the wait or waitpid system call. For more finer process synchronization, use semaphores.

Related

How to invoke an executable in the path /usr/bin using a C++ program?

I have an GUI based executable in the path /usr/bin in the linux machine
This executable takes three arguments - two integer values and one char
Can you let me know how to invoke and run this executable from a user space C++ program
Not leaving this unanswered for no reason
pid_t runprocess(int arg1, int arg2, char arg3)
{
static const char program[] = "/usr/bin/...";
char arg1c[12];
char arg2c[12];
char arg3c[2];
sprintf(arg1c, "%d", arg1);
sprintf(arg2c, "%d", arg2);
arg3c[0] = arg3;
arg3c[1] = 0;
pid_t pid = vfork();
if (pid == 0) {
signal(SIGHUP, SIG_IGN); /* since it's a GUI program, detach from console HUP */
close(0); /* and detach from stdin */
if (open("/dev/null", O_RDWR)) _exit(137); /* assertion failure */
execl(program, program, arg1c, arg2c, arg3c, NULL);
_exit(errno);
}
return pid;
}
Build arguments as strings, fork and exec it. Trivial really. Don't forget to wait().
Since the child process is a GUI process, we detach HUP from the terminal we may or may not be running on and replace stdin with /dev/null.

Kill a process after creating not working

I've somehow written a program to spawn a process but unable to kill it after 2 seconds automatically( It actually does not kill):
void createproc() {
//WaitForSingleObject(&processInfo.hProcess, INFINITE)
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));
wchar_t commandline_args[] = L"\"C:\\ddnvnc\\WebServer.exe\" ";
if (!CreateProcess(NULL, // No module name (use command line)
commandline_args, // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi) // Pointer to PROCESS_INFORMATION structure
)
{
printf("CreateProcess failed (%d).\n", GetLastError());
MessageBox(NULL,
_T("Failed"),
_T("Windows Desktop Guided Tour"),
NULL);
}
Sleep(2000);
CloseHandle(&pi.hThread);
TerminateProcess(&pi.hProcess,0);
MessageBox(NULL,
_T("KIlled"),
_T("Windows Desktop Guided Tour"),
NULL);
}
What I want is to spawn and kill the process after 2 seconds, this will be in an infinite loop.
CloseHandle(&pi.hThread);
TerminateProcess(&pi.hProcess,0);
Use pi.hThread instead of &pi.hThread. Note that the order should be reversed.
You can use WaitForSingleObject instead of Sleep, and terminate the process only if it's not terminated already (for example by the user)
//Sleep(2000);
//TerminateProcess(pi.hProcess, 0);
if(WaitForSingleObject(pi.hProcess, 1000) == WAIT_TIMEOUT)
TerminateProcess(pi.hProcess, 0);
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);

How to make system() function unblocking?

I am calling an executable from another executable in android Linux. Following is the relevant code:
...
int status = system("/system/bin/executable");
...
My requirement is not to wait for the executable to complete its execution. Means I want to run executable independent of the executable that calls it.
I have searched over the internet and didn't find how to make this system call non-blocking. Please help me to resolve it.
The system() function, without error handling, looks like this:
int system(char const *cmdline)
{
pid_t pid = fork();
if(pid == 0)
{
char const *argv[] = { "sh", "-c", cmdline, NULL };
execve("/bin/sh", argv, NULL);
_exit(1);
}
else
{
int status;
waitpid(pid, &status, 0);
return status;
}
}
The command itself is parsed by the shell, so you can use the normal & suffix to send the command into the background. The shell then terminates immediately, the background program is reparented to PID 1 (so your program isn't responsible for collecting the zombie), and system() returns.
I am able to achieve non-blocking with following code:
if (fork() == 0)
{
char *args[] = {..., NULL};
char *env[] = {..., NULL};
if (execve("/system/bin/executable", args, env) == -1)
print("Error: [%d]", errno);
}
There are few importants thing here:
fork() will create a new process. So from line if(fork() == 0), there will be 2 process running in the same space of main program.
Both processes continue executing from the point where the fork( ) calls returns execution to the main program..
fork() == 0 will let only child process in the if condition.
execve(..) will replace child process program(which is its parent program from which it copied by fork command) with /system/bin/executable.
execve(..) will not return if it get success in runing the executable else return -1.
In case of execve(..) failure the errno will be filled with the actual error.
Please correct me if I am wrong. I hope it will help someone.

How to propagate signal in C from parent to child which are in own process group?

Suppose I have 10 child processes which are moved to their own process group by setpgid(0,0) just before the exec. (Each child also has children which are also in their own process group.)
My foreground process gets ctrl-c SIGINT signal and I want to propagate it to the all child processes (all children are in different group). How to do that?
hope that quick draft better explain my problem.
void handler(int signal) {
// resend SIGINT to all childs but childs are in different pgid
}
int main(int argc, char* argv[]){
struct sigaction sa;
sa.sa_handler = &handler;
sigaction(SIGINT, &sa, NULL);
pid_t pid[SIZE];
int i = 0;
// if argv is ge 2;
for (;i < SIZE; i++) // SIZE is number of the elements in argv
{
pid[i] = fork();
if(pid[i] == 0)
{
setpgid(0,0);
// execv self here but with one less element in argv;
}
}
while(1){}; // infinity loop (waits for ctrl-c from foreground process)
// prints to the terminal pid and pgid
// waits here for all childs to finish and then close self
}
What about forwarding the signal in the signal handler of main process, manually. Maybe you can provide some code snippet to clarify the situation you're in.
void signalHandler(int signum)
{
kill(child_pid,signum);
//other stuff
}

Solaris thr_join vs posix pthread_join

In Solaris, thr_join documentation states the following:
int thr_join(thread_t thread, thread_t *departed, void
**status);
If the target thread ID is 0, thr_join() finds and returns
the status of a terminated undetached thread in the process.
Is POSIX pthread_join equivalent?
int pthread_join(pthread_t thread, void **status);
suspends processing of the calling thread until the target thread completes
How can I use pthread_join in case of thr_join when I would like to know which child thread have terminated among many.
Is there any other alternative?
In other words, if a parent thread spawns N child threads, how do the parent thread know by polling or something else which thread has exited / terminated?
Is POSIX pthread_join equivalent?
Yes, it's equivalent. Well, close enough. You can see the differences in the implementation:
int
thr_join(thread_t tid, thread_t *departed, void **status)
{
int error = _thrp_join(tid, departed, status, 1);
return ((error == EINVAL)? ESRCH : error);
}
/*
* pthread_join() differs from Solaris thr_join():
* It does not return the departed thread's id
* and hence does not have a "departed" argument.
* It returns EINVAL if tid refers to a detached thread.
*/
#pragma weak _pthread_join = pthread_join
int
pthread_join(pthread_t tid, void **status)
{
return ((tid == 0)? ESRCH : _thrp_join(tid, NULL, status, 1));
}
They're even implemented using the same internal function.
But you don't want to use Solaris threads. Just use POSIX threads.

Resources