Search code examples
csystems-programming

Is there a way club two Linux command together in system() function in C?


I wanted to execute who command and cut out the needed info like who | cut -d " " -f 1,21,23 but by using the system() function in c.

I tried doing system("who | cut -d " " -f 1,21,23") which did not work.

The code:

#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]);
        }
    }
    }
}

The output:

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

Solution

  • With "who | cut -d " " -f 1,21,23" you have two strings: "who | cut -d " and " -f 1,21,23". They are concatenated to "who | cut -d -f 1,21,23".

    To include double-quotes inside C strings you need to escape them with the backslash: "who | cut -d \" \" -f 1,21,23".