简体   繁体   中英

Disallowing printf in child process

I've got a cmd line app in C under Linux that has to run another process, the problem is that the child process prints a lot in a comand line and the whole app gets messy.

Is it possible to disallow child process to print anything in cmd line from parent process? It would be very helpful to for example being able to define a command that allows or disallows printing by a child process.

There's the time-honoured tradition of just redirecting the output to the bit bucket (a) , along the lines of:

system("runChild >/dev/null 2>&1");

Or, if you're doing it via fork/exec , simply redirect the file handles using dup2 between the fork and exec .

It won't stop a determined child from outputting to your standard output but it will have to be very tricky to do that.


(a) I'm not usually a big fan of that, just in case something goes wrong. I'd prefer to redirect it to a real file which can be examined later if need be (and deleted eventually if not).

Read Advanced Linux Programming then syscalls(2) .

On recent Linux, every executable is in ELF format (except init or systemd ; play with pstree(1) or proc(5) ) is running in a process started by fork(2) (or clone(2) ...) and execve(2) .

You might use cleverly dup2(2) with open(2) to redirect STDOUT_FILENO to /dev/null (see null(4) , stdout(3) , fileno(3) )

I've got a cmd line app in C under Linux that has to run another process, the problem is that the child process prints a lot in a comand line

I would instead provide a way to selectively redirect the child process' output. You could use program arguments or environment variables (see getenv(3) and/or environ(7) ) to provide such an option to your user.

An example of such a command program starting and redirecting subprocesses and redirecting them is your GCC compiler (see gcc(1) ; it runs cc1 and as(1) and ld(1) ...). Consider downloading and studying its source code.

Study also -for inspiration- the source code of some shell (eg sash ), or write your own one.

Could be solved by scrapping the printf entirely and using a function that will only print if its called on father process

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

void print(char *msg,int dadid) {
    if(dadid!=getpid()){
        printf(msg);
    }
}

int main(){
    int dadid=getpid();
    int son = fork();

//code
//code

print("huhuhu",dadid);
return 0;
}

also containing yr prints in the previously mentioned check could also work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM