c - 有没有办法在 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 ...
解决方案
"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"
。
推荐阅读
- javascript - 过滤器不适用于第三个子级别(嵌套级别)
- c++ - 如何从控制台启动可执行文件并使用 Qt 读取输出
- python - 如何使用python遍历二进制块并在文件末尾停止?
- php - Laravel 5.4 - 如何使用 EDI 供应商库
- angular - Angular 7+,从父组件调用子组件的方法好吗?
- azure - 将资源组从开发公司转移到客户公司
- java - 如何为 selenium +TestNG+java 项目设置魅力?
- javascript - 将 jQuery 搜索限制为特定容器,例如 h 和 p 标签
- javascript - 下拉固定位置和格式不起作用
- android - Play 商店报告“您的设备与此版本不兼容”但它通过 adb 安装在 onePlus 上就好了