How can I call awk or sed from within a c program?

How can I call awk or sed inside a c program? I know that I can use exec (), but I do not want to deal with fork () and all this muck.

+5
source share
5 answers

Will it popenwork? It starts the process, then you read / write with FILE*handle

+7
source

Then your choice system()or use of any library that completes the spawning process for you. The last, or hard way, that you wanted to avoid, is recommended if you want subtle control over errors, pipes, etc.

+5
source

system() .

, . , , . UNIX, script, .

, C-, Bourne. , , , , . . ...

.

+3

libc system popen, :

int system(cont char *command) {
    const char *argv[4] = {"/bin/sh", "-c", command};
    int status;
    pid_t child = fork();
    if (child == 0) {
        execve(argv[0], argv, NULL);
        exit(-1);
    }
    waitpid(child, &status, 0);
    return status;
}

FILE *popen(const char *command, const char *type) {
    int fds[2];
    const char *argv[4] = {"/bin/sh", "-c", command};
    pipe(fds);
    if (fork() == 0) {
        close(fds[0]);
        dup2(type[0] == 'r' ? 0 : 1, fds[1]);
        close(fds[1]);
        execve(argv[0], argv, NULL);
        exit(-1);
    }
    close(fds[1]);
    return fdopen(fds[0], type);
}

( , )

If you need more subtle control over the processing of arguments (instead of going through sh), or you want to control more than one of them {stdin, stdout, stderr}, you will have to write it yourself or find a library. But the standard library covers most use cases.

+1
source

You can do this by calling system (). This Thread is a good example.

+1
source

All Articles