Operating System - HP-UX
1834395 Members
1690 Online
110066 Solutions
New Discussion

How to invoke another c program inside a c program

 
SOLVED
Go to solution
Xiaoming Zhang
Contributor

How to invoke another c program inside a c program

As a control c program, it checks some condition. When the condition exists, it should kick of another processing c program. What command/code I should use inside the control c program to start the processing c program?

Thanks.
2 REPLIES 2
Kenneth Platz
Esteemed Contributor
Solution

Re: How to invoke another c program inside a c program

There are actually 3 different methods for starting up a program from within another program, depending on what you want to do with the program in question.

First, you can use the system() call. This will execute another program, wait for it to terminate, and then return the exit code of that application to your program. For example:

system( "/usr/bin/ls" );

This will execute /usr/bin/ls and your program will wait until the "ls" program terminates.

The second option is to use the exec() family of functions, (usually in conjunction with fork()). fork() will create a new process (which can run independently from its parent), and exec() causes the currently running process to be replaced with the program specified. For example:


if ( fork() == 0 ) {
/* First child */
setpgrp();
fclose( stdin );
fclose( stdout );
fclose( stderr );
if ( fork() ) exit(0);
/* second child */
exec( "/usr/local/bin/myprogram" );
}

The above code is similar to what is found in many daemon processes -- this will start a program completely independent of its parent.

The third option involves using popen() to open a process and redirect its standard input and/or output to a file descriptor that we can read and/or write to. This is useful if you want to actually examine the output of that command. For example:

fp = popen( "/usr/bin/ls", "r" );
while( !feof( fp ) ) {
fgets( buf, bufsiz, fp );
/* Do useful stuff here */
}

I hope this helps.
I think, therefore I am... I think!
Xiaoming Zhang
Contributor

Re: How to invoke another c program inside a c program

Thanks for quick response. The following function in a c program worked:

void startprocs()
{
if ( fork() == 0 )
execlp("procsudf.exe", (char *)0);
}