繁体   English   中英

您如何将 arguments 用于 execv || execl 运行一个程序或 pipe 另一个

[英]how do you take arguments for execv || execl to run either one program or pipe another

好的,我不想通过 arguments 我知道,但我想弄清楚如何从终端传递这些 arguments,你从哪里学到这个?

int 
main(int argc, char **argv) {

    int infd, outfd, bytes;
    char buf[SIZE];

    //I WILL READ FILES HERE 
    while((bytes = read(infd, buf, SIZE)) > 0) {
        write(outfd, buf, bytes);
    }

    int fd[2];
    if (pipe(fd) == -1) return 1;

    int pid1 = fork();
    if (pid1 < 0) return 2; 

    if (pid1 == 0) {
        dup2(fd[0], STDIN_FILENO);
        close(fd[0]);
        close(fd[1]);
        execvp("How do i take arguments here?");
        // Example, I am showing an example with execl but i would like to use execv
        // Assuming wcat is my written program. Am writing wcat in another file? or 
        // can i call the wcat function if wcat was as an argument? I tried something like below
        // Note: that i tried :
        /*
            execlp("./wcat", argv[1], argv[2], argv[3]); but this does nothing 
        */
        execlp("wcat", "wcat", "file1", "file2", "file3", NULL);
        if ((strcmp(argv[0], "wcat"), 0)) { // i did this but nope 
            // do something
        }
    }

    int pid2 = fork();
    if (pid2 < 0) return 3;

    if (pid2 == 0) {
        dup2(fd[2], STDIN_FILENO);
        close(fd[0]);
        close(fd[1]);
        execvp("How do i take arguments here?");
        // Note: that i tried :
        /*
            execlp("./ww", argv[1], NULL); but this does nothing 
        */
        if ((atoi(argv[1], "pass integer here"), 0)) { // i did this but nope 
            // do something
        }
        // Example, I am showing an example with execl but i would like to use execv
        execlp("use my word-wrap program", " pass second arguments as an integere");
    }
 // you have to close the both file descriptors for the program to end
    close(fd[0]);
    close(fd[1]);
    // calling waitpid for fd[1] to work before starting fd[2]
    waitpid(pid1, NULL, 0);
    waitpid(pid2, NULL, 0);
    return 0;
}

我想在终端上运行它:


./wcat 文件1 文件2 文件3 |./ww 50


请任何知识都会有所帮助。 我的其他程序都完成了。 我只需要在终端上运行它,我可以在文件中传递 arguments,这很好,但我想在终端上运行它。

execlp接受可变数量的 arguments 类型的const char *由 NULL 终止:

execlp("./wcat", "./wcat", "first arg", "second arg", NULL);

实际问题是您希望执行execlp()调用之后的代码。 它不会因为您指定的程序现在正在运行:

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

int main() {
    execlp("/bin/bash", "/bin/bash", "-c", "echo hello", 0);
    printf("world\n");
    return 0;
}

只会打印:

hello

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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