C 有没有办法实现system()函数
我试图重新实现system()库函数。但是,如果我将ps或ls命令作为一个参数从main传递,我就不会得到输出。谢谢 原始代码:C 有没有办法实现system()函数,c,linux,unix,C,Linux,Unix,我试图重新实现system()库函数。但是,如果我将ps或ls命令作为一个参数从main传递,我就不会得到输出。谢谢 原始代码: #include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/wait.h> #include<error.h> #define buf_size 512 int main(int argc, char *argv[]) {
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<error.h>
#define buf_size 512
int main(int argc, char *argv[])
{
pid_t pid;
char *buf[buf_size];
int ret = 0;
char ch;
int i = 0;
int j = 0;
if (argc != 2)
error(1, 0, "Too many of less number of arguments\n");
for (i = 1; i < argc; i++) {
*(buf + j) = argv[i];
j++;
}
buf[j] = '\0';
pid = fork();
if (pid == -1) {
error(1, 0, "error in creating the sub-process\n");
} else if (pid == 0) {
execv("bin/sh", buf);
} else {
wait(NULL);
}
}
你离解决方案不远了 你错过的主要事情是你应该启动
/bin/sh-cls
,而不是bin/shls
更正:
- 不要写入
buf[j]=“0”相反,我增加了for循环的大小(注意,
I
没有意义,它应该是buf[j]='\0';
它可以工作,但是它会误导人,因为您使用buf[j]=NULL;
作为指针。您应该测试'\0'
是否存在(关于bin/sh
)添加一些/bin/sh
在perror(“…”)
之后:如果失败,你将开始解释原始海报对这篇文章所做的大量编辑已经做出了这些评论,下面的答案是完全不相关的。我正在将原始代码添加到这篇文章中,以便所有这一切再次变得有意义。关于execv
的警告使用:what I第一个参数是什么?OP有argv
,而不是“\0”
。它们非常不同。两者都不正确,但我不相信OP有什么会导致错误。“\0”
int main(int argc, char *argv[]) { pid_t pid; int ret; if (argc != 2) error(1, 0, "Too many of less number of arguments\n"); pid = fork(); if (pid == -1) { error(1, 0, "error in creating the sub-process\n"); } else if (pid == 0) { ret = execv("/bin/sh", argv); if (ret == -1) error(1, 0, "error in execv() system call\n"); } else { wait(NULL); } }
#include<stdio.h> #include<unistd.h> #include<sys/types.h> #include<sys/wait.h> #include<error.h> int main(int argc, char *argv[]) { pid_t pid; char * buf[4]; if (argc != 2) error(1, 0, "Too many of less number of arguments\n"); buf[0] = "sh"; buf[1] = "-c"; buf[2] = argv[1]; buf[3] = NULL; pid = fork(); if (pid == -1) { error(1, 0, "error in creating the sub-process\n"); } else if (pid == 0) { execv("/bin/sh", buf); perror("execv"); } else { wait(NULL); } }