system
int system(const char *command);
system()函數的返回值如下:
成功,則返回進程的狀態值;
當sh不能執行時,返回127;
失敗返回-1;
其實是封裝后的exec,函數源代碼在子進程調用exec函數,system使用更加簡單,用法就是將./ 和后的內容(要執行的指令)放進代碼中去。和exec不同的是,它運行完后還會返回到原來的代碼處
比如:
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
//int execl(const char*path,const char *arg,..)
int main()
{printf("this pro get system date: \n");if(system("date")==-1){printf("execl failed \n");perror("why");}printf("after execl\n");return 0;
}
運行結果:this pro get system date: Mon Sep 21 21:37:45 CST 2020after execl
代碼示例
#include<stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
int main()
{pid_t fpid;int data;while(1){printf("please input a data\n");scanf("%d",&data);if(data==1){fpid=fork();if(fpid>0){wait(NULL);}if(fpid==0){// execl("./changedata","changedata","config.txt",NULL);system("./changedata config.txt");}}else{printf("do nothing\n");}}return 0;
}
popen函數
#include <stdio.h>
FILE *popen(const char *command, const char *type);
int pclose(FILE *stream);
比system好的是可以獲取運行的輸出結果。
參數說明:
type參數只能是讀或者寫中的一種,得到的返回值(標準I/O流)也具有和type相應的只讀或只寫類型。如果type是"r"則文件指針連接到command的標準輸出;如果type是"w"則文件指針連接到command的標準輸入。
command參數是一個指向以NULL結束的shell命令字符串的指針。這行命令將被傳到bin/sh并使用-c標志,shell將執行這個命令。
返回值:
如果調用成功,則返回一個讀或者打開文件的指針,如果失敗,返回NULL,具體錯誤要根據errno判斷。
int pclose(FILE* stream)
參數說明:
stream: popen返回的文件指針
返回值:
如果調用失敗,返回-1
作用:
popen())函數用于創建-個管道:其內部實現為調用fork產生一個子進程,執行一個shell以運行命令來開啟一個進程這個進程必須由pclose()函數關閉。
代碼演示
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
//int execl(const char*path,const char *arg,..)
//size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
int main()
{char ret[1024]={0};FILE *fp;fp=popen("ps","r");int n_read=fread(ret,1,1024,fp);//將popen的返回值讀取到ret中printf("read ret:%d,popen return :%s\n",n_read,ret);return 0;
}