Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative of system() in c Linux to execute a terminal command on linux

Tags:

c

linux

misra

I want to execute a terminal command of Linux in a C program. Currently I am using system() function but I want to use any other as the system() function is banned as per MISRA.

For example, how can I replace

 system("hwclock --systohc --utc");
like image 858
BKT Avatar asked Jun 05 '15 09:06

BKT


2 Answers

First you can use fork()to create a child process,then in the child process,you can call exec() to execute command what you want.
There is a simple example:

$ chmod u+x command.sh 
$ cat command.sh  

#!/usr/bin/env bash
ls -l

************* test.c ****************

#include<unistd.h>
int main(void)
{
  execl("./command.sh","command.sh",(char*)0);
  return 0;
}
like image 116
Ren Avatar answered Oct 03 '22 11:10

Ren


You can make use of fork() and then look up for exec() family of functions.

Alternatively, you may want to have a look at popen() also.

like image 28
Sourav Ghosh Avatar answered Oct 03 '22 10:10

Sourav Ghosh