execlp multiple “programs”

眉间皱痕 提交于 2020-01-21 15:05:46

问题


I want to run something like

cat file.tar | base64 | myprogram -c "| base64 -d | tar -zvt "

I use execlp to run the process.

When i try to run something like cat it works, but if i try to run base64 -d | tar -zvt it doesn't work.

I looked at the bash commands and I found out that I can run bash and tell him to run other programs. So it's something like:

execlp ("bash", "-c", "base64 -d | tar -zvt", NULL);

If I run it on the terminal, it works well, but using the execlp it dont work. If I use execlp("cat", "cat", NULL) it works.

Someone knows how to use the -c param on execlp to execute multiple "programs"? I cant use system because i use pipe and fork.

Now i noticed, if i try to use execlp("bash", "bash", "-c", "base64", NULL)... nothing happens. If i use execlp("cat", NULL) it's ok.. I'm writing to the stdin... i don't know if its the problem with the bash -c base64.. because if i run on the terminal echo "asd" | bash -c "cat" it goes well


回答1:


The first "argument" is what becomes argv[0], so you should call with something like:

execlp("bash", "bash", "-c", "base64 -d | tar -zvt", NULL);

Edit A small explanation what the above function does: The exec family of functions executes a program. In the above call the program in question is "bash" (first argument). Bash, like all other programs, have a main function that is the starting point of the program. And like all other main functions, the one in Bash receives two arguments, commonly called argc and argv. argv is an array of zero-terminated strings, and argc is the number of entries in the argv array. argc will always be at least 1, meaning that there is always one entry at argv[0]. This first entry is the "name" of the program, most often the path of the program file. All other program arguments on the command line is put into argv[1] to argv[argc - 1].

What execlp does is use the first argument to find the program to be executed, and all the other arguments will be put into the programs argv array in the order they are given. This means that the above call to execlp will call the program "bash" and set the argv array of Bash to this:

argv[0] = "bash"
argv[1] = "-c"
argv[2] = "base64 -d | tar -zvt"

Also, argc of Bash will be set to 3.

If the second "bash" is changed to "foo", then argv[0] of Bash will be set to "foo" as well.

I hope this clears it up a little bit.



来源:https://stackoverflow.com/questions/8819135/execlp-multiple-programs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!