Execute and Capture one program from another - c

In win32 programming in C:
Whats the best way to execute a win32 console program within another win32 program, and have the program that started the execution capture the output? At the moment I made the program redirect output to a file, but I am sure I must be able to open some sort of pipe?

Use the CreateProcess Win32 API to start the child process.
Pass to it a STARTUPINFO structure with hStdInput, hStdOutput and hStdError handles set to file handles you opened (either real files or memory mapped files should work). You don't need to specify all three, you can redirect only the ones you really need; most common case is hStdOutput.
If you want to communicate with the child process (through hStdInput), you need to wait for it to initialize by calling WaitForInputIdle.

Related

How do I detect if I'm a first instance or send a IPC message to previous instance of same app?

My app is suppose to run long term (usually idling). If I try to open a second app (or trigger the app via global hotkey) I'd like my existing instance to receive some kind of IPC message and bring itself to the front. How do I do this on linux? The problem I've been running into is if I hold a global lock it doesn't automatically free when the instance close (usually I unlock it but an app can crash). If I try to use mkfifo I have no idea if I'm the first instance or not and every solution I can think of seems to require a lot of code and usually that's a sign to me I might be doing something wrong
There are many IPC primitives, all possible to use.
A simple one is using a named pipe: If the pipe doesn't exist then the program creates it and starts as usual. Then it polls the pipe at regular intervals to see if something can be received on the pipe, in which case the program receives it (and discards it) and puts itself to the "front".
If, on the other hand, the named pipe exists, then the program sends a simple dummy message through it, and exits.
I would use a flag file, e.g. /run/service-name/pid with PID of the first running instance. A new instance would check this file, if it does not exists, create it, if it does, send a SIGUSR1 to the PID in the file.
#Some programmer dude's answer above provides a bit more of flexibility.

Is it possible to pipe() within a program in C?

Let's say that there is an existing program that listens on stdin for it's inputs. I want to create a pthread within the same program that is now the one to listen to stdin, and depending on what comes through, let it go through to the original program.
For this, I would create a pipe(), and configure the pthread to write to the input file descriptor, and the original program to listen to the output descriptor. Is this a correct way to have this done? I understand piping between processes, but is it possible to pipe like this within a single process?
Sure, you can use pipe(), but the data has to pass through the kernel even though both the end points are within the same process.
If you have source code for this (which I assume you have) and you don't mind making non-trivial changes, and performance is a priority for you, I would suggest using shared memory to send the data to the original program. It will be much faster than using pipe()

C -Run console app within another console app

I need to build a console app (A) that shows a menu where you can select an option and it will execute previous console apps (B,C,D...) that i built in class. How can i go about that? can i call these previous apps or do i need to add them into my program?, Because it needs to include about 15 previous projects and i think that's a lil' bit excesive. i know fOpen() is used to open txt files i don't know if it works with apps. FILE *fopen( const char * filename, const char * mode );
You will want to start a child process, then redirect its stdout to your own process' output, and its stdin to your own process' input - but presumably you'll want to intercept certain keystrokes to allow a user to terminate the child process without killing your own.
In a POSIX environment you would use popen() which gives you a pipe for redirecting input and output. On Windows you would use CreatePipe instead. Windows does not implement the POSIX popen() but it does have an internal function _popen but I understand it has different semantics.
But there is no function or capability in the C Standard Library to pipe between processes (C itself doesn't even require the computer to support a concept of a "process" either - it's a surprisingly platform-agnostic language and library - you can even use it for a platform without a malloc implementation).
Anyway, if you're okay with targeting just Windows, or for writing a wrapper library, I recommend you read this MSDN article which describes exactly what you're looking to do:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499(v=vs.85).aspx
Creating a Child Process with Redirected Input and Output
The example in this topic demonstrates how to create a child process using the CreateProcess function from a console process. It also demonstrates a technique for using anonymous pipes to redirect the child process's standard input and output handles. Note that named pipes can also be used to redirect process I/O.
you can use the function system and path the program
example :
system ("ConsoleProgram2.exe"); // if it were in the same path
system() is a shell script method so you can use it as any way you want but people say that is a bad thing to use system function but in you'r case i don't see a problem.

change terminal directory using c language

i am trying to change the directory of my linux terminal using c language. the thing is i am using threads. i have tried to use chdir() but its not working, n yes chdir() is also a process function.
Actually the thing i am trying to implement is, i am trying to make a multi threaded program which compiles Linux kernel, and that is not possible without specifying directories( i have tried to do it without specifying directories but failed :) )
can anybody help me out with this issue?
Thanks in advance :)
You can't! No process can change the working directory of another. A process can only change its own WD. When you launch an external command such like your C program, then a new process is launched.
The cd command of your shell is an internal one.
It isn't very clear what you are trying to achieve. It appears that somehow you wish to emulate the behaviour of a script (or the make tool) using a C program, that is to say having the C program you wrote launch new processes (using system or perhaps a combination of fork and exec*). If that is the case, then what you actually want is to modify the environment variables of these processes for them to find the files they need. A forked process will inherit the environment of its parent, so all you need is to use getenv, putenv, setenv and unsetenv to retrieve and set the environment variables you want to add, update or remove; or you may use the specific execve, execvpe which let you specify exactly what environment should be available to the new program.
references:
fork system call
exec family of system calls
unix environment

Call same instance of a program?

I am creating a C program that is called from a shell script when a specific event is occurring. The C program gets an argument from the shell script like this:
> ./c-program.bin HELLO
Now the C program is running until it recieves a specific character as an argument. The problem is that if a second event occurs, and the C program is now called like this:
./c-program.bin WORLD
Then it is a new instance of the program that is started that knows nothing about the string from the first event. What i would like to achieve is something like this:
[EVENT0] ./c-program.bin HELLO
[EVENT1] ./c-program.bin WORLD
[EVENT2] ./c-program.bin *
c-program output:
HELLO WORLD
Any ideas on how to only have one instance of the program? The platform is Linux. The project is in its planning fase therefore, i do not have any specific code so far, i am trying to sort out the different problems first.
In outline, you have a magical "output everything" argument and want to accumulate all other arguments across multiple calls until you get the request to be magical? Easy enough, but requires some shared state. First hack would put that state in the filesystem (a database would be better, but is more complex).
I would use a pid file stored somewhere.
If you start the program, it should unsure that an other one is not running (using the pid file + verification). If not, create a named pipe where he would read data. Then put it in background, thanks to sub-process (fork) for instance.
Then an other instance is started, finding the pidfile and detecting that an instance is already launched. This second program would send argv[i] to the named pipe, so the first instance should print the data.
An other idea is to use a unix socket in a given file, like mysql.sock for instance.
Your program should check if another instance is running, and if that is the case pass its argument to that instance, and exit. The first instance to come alive should become the "server", that is stay alive ready to receive data. You can use shared memory or pipes for passing data between processes.
What you want isn't very clear. I think you are after a long-running process that accumulates "messages" of some sort, and then allows retrieval of those messages.
Here's one possible solution:
Try to create a fifo at a known location. If this succeeds, fork a daemon that listens on that fifo, accumulating messages until it receives a *, at which point it echos all messages back to the fifo, including the *.
The original process (whether it spawned a daemon or not) opens the fifo for writing, and pushes the message.
If the argument was *, it then reads the fifo and outputs everything it gets until it receives the echoed *.
You either need a intermediate app, or probably a separate shell script
The intermediate script would cache the parameters to disk until you pass a '*', at which point it then passes the entire cached string to the final c program.
So your first script would call the second script, passing:
secondscript HELLO
secondscript WORLD
secondscript *
When the second script receives a parameter of * it passes all the previous parameters to your c program
./c-program.bin HELLO WORLD
Compared to the later answers, this still seems by far the easiest option. You could script this in 10 minutes. Pseudocode for the intermediate app/script:
passedstring = args[0]
if passedstring = "*"
string cache = readcontents(cachefile)
call c program passing cache
clearcontents(cachefile)
else
append(cachefile, passedstring)
If however you want the challenge of developing a fancy dancin app that can check for another version of itself in memory, then pass stuff around in sockets, go for it :)

Resources