c - 如何定义系统()

标签 c bash operating-system

所以我要定义system()函数!这是我的功能:

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

void mySystem (char *command)
{    
    execlp (command, command, (char*) 0);
}

int main (int argc, char* argv[])
{    
    for (int i = 1; i < argc; i++) 
    {
        char command[50];
        strcpy(command, argv[i]);
        mySystem(command);
    }

    return 0;
}

然后我试了一下,结果是这样的:

gcc exe6.c;
./a.out ls ls

在这种情况下,它只执行一次 ls。

./a.out "ls -l"

在这种情况下不做任何事情。我做错了什么?

最佳答案

man page实际上告诉你怎么做:

The system() library function uses fork(2) to create a child process that executes the shell command specified in command using execl(3) as follows:

execl("/bin/sh", "sh", "-c", command, (char *) 0);

system() returns after the command has been completed.

关于c - 如何定义系统(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49479039/

相关文章:

c++ - 如何为特定头文件中声明的函数强制执行 cdecl 调用约定

c - c中的字符串比较

bash - 使用 bash 下载图像直到 url 无效

bash - Bash 中的错误处理

Bash 命令以冒号开头,在等号前有另一个冒号

python - 在 Python 中编译 C++ 程序时 try catch 由于语法引起的操作系统错误

java - 分布式系统中的发起节点

c - 使用指针的程序运行不正常

c - 修改C字符串常量?

operating-system - "Protection rings"和 "CPU modes"是一回事吗?