管道popen和pclose的实例使用
單次輸出?
/*取得當前目錄下的文件個數*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>
#define MAXLINE 1024
int main()
{
?? ?char result_buf[MAXLINE], command[MAXLINE];
?? ?int rc = 0; // 用于接收命令返回值
?? ?FILE *fp;
?? ?/*將要執行的命令寫入buf*/
?? ?snprintf(command, sizeof(command), "ls ./ | wc -l");
?? ?/*執行預先設定的命令,并讀出該命令的標準輸出*/
?? ?fp = popen(command, "r");
?? ?if(NULL == fp)
?? ?{
?? ??? ?perror("popen執行失敗!");
?? ??? ?exit(1);
?? ?}
?? ?while(fgets(result_buf, sizeof(result_buf), fp) != NULL)
?? ?{
?? ??? ?/*為了下面輸出好看些,把命令返回的換行符去掉*/
?? ??? ?if('\n' == result_buf[strlen(result_buf)-1])
?? ??? ?{
?? ??? ??? ?result_buf[strlen(result_buf)-1] = '\0';
?? ??? ?}
?? ??? ?printf("命令【%s】 輸出【%s】\r\n", command, result_buf);
?? ?}
?? ?/*等待命令執行完畢并關閉管道及文件指針*/
?? ?rc = pclose(fp);
?? ?if(-1 == rc)
?? ?{
?? ??? ?perror("關閉文件指針失敗");
?? ??? ?exit(1);
?? ?}
?? ?else
?? ?{
?? ??? ?printf("命令【%s】子進程結束狀態【%d】命令返回值【%d】\r\n", command, rc, WEXITSTATUS(rc));
?? ?}
?? ?return 0;
}
持續輸出
/*取得ping 命令*/
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/wait.h>
#include <string.h>
#define MAXLINE 1024
int main()
{
?? ?char result_buf[MAXLINE], command[MAXLINE];
?? ?int rc = 0; // 用于接收命令返回值
?? ?FILE *fp;
?? ?/*將要執行的命令寫入buf*/
?? ?snprintf(command, sizeof(command), "ping 192.168.0.101");
?? ?/*執行預先設定的命令,并讀出該命令的標準輸出*/
?? ?fp = popen(command, "r");
?? ?if(NULL == fp)
?? ?{
?? ??? ?perror("popen執行失敗!");
?? ??? ?exit(1);
?? ?}
?? ?while(fgets(result_buf, sizeof(result_buf), fp) != NULL)
?? ?{
?? ??? ?/*為了下面輸出好看些,把命令返回的換行符去掉*/
?? ??? ?if('\n' == result_buf[strlen(result_buf)-1])
?? ??? ?{
?? ??? ??? ?result_buf[strlen(result_buf)-1] = '\0';
?? ??? ?}
?? ??? ?printf("輸出【%s】\r\n", result_buf);
?? ?}
?? ?/*等待命令執行完畢并關閉管道及文件指針*/
?? ?rc = pclose(fp);
?? ?if(-1 == rc)
?? ?{
?? ??? ?perror("關閉文件指針失敗");
?? ??? ?exit(1);
?? ?}
?? ?else
?? ?{
?? ??? ?printf("命令【%s】子進程結束狀態【%d】命令返回值【%d】\r\n", command, rc, WEXITSTATUS(rc));
?? ?}
?? ?return 0;
}
?
?
新人創作打卡挑戰賽發博客就能抽獎!定制產品紅包拿不停!總結
以上是生活随笔為你收集整理的管道popen和pclose的实例使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: gezabo变黑闪退,报错[gazebo
- 下一篇: 使用hexo创建blog