首页 > 解决方案 > 有没有办法在 C 的 system() 函数中将两个 Linux 命令组合在一起?

问题描述

我想执行who命令并删除所需的信息,例如who | cut -d " " -f 1,21,23使用 c 中的 system() 函数。

我试过做system("who | cut -d " " -f 1,21,23")这行不通。

编码:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define ErrorBC -69
int main(int argc, char* argv[]){
    if(argc < 2){
        printf("No arguments passed\n");
        return -69;
    }
    else{
        int i=0;
        for(i=1;i<argc;i++){
        if((strcmp("kernel",argv[i]))==0){
            system("uname -s -r");
        }
        else if(((strcmp("ulog",argv[i]))==0)){
                system("who | cut -d " " -f 1,21,23");
        }
        else{
            printf("%s is not a valid options\n",argv[i]);
        }
    }
    }
}

输出:

c99 test.c
/usr/sahil: ./a.out ulog
Usage: cut {-b <list> [-n] | -c <list> | -f <list> [-d <char>] [-s]} file ...

标签: csystems-programming

解决方案


"who | cut -d " " -f 1,21,23"你有两个字符串"who | cut -d "" -f 1,21,23". 它们连接到"who | cut -d -f 1,21,23".

要在 C 字符串中包含双引号,您需要使用反斜杠对它们进行转义"who | cut -d \" \" -f 1,21,23"


推荐阅读