管道popen和pclose的实例使用
單次輸出?
/*取得當(dāng)前目錄下的文件個(gè)數(shù)*/
#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;
?? ?/*將要執(zhí)行的命令寫入buf*/
?? ?snprintf(command, sizeof(command), "ls ./ | wc -l");
?? ?/*執(zhí)行預(yù)先設(shè)定的命令,并讀出該命令的標(biāo)準(zhǔn)輸出*/
?? ?fp = popen(command, "r");
?? ?if(NULL == fp)
?? ?{
?? ??? ?perror("popen執(zhí)行失敗!");
?? ??? ?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);
?? ?}
?? ?/*等待命令執(zhí)行完畢并關(guān)閉管道及文件指針*/
?? ?rc = pclose(fp);
?? ?if(-1 == rc)
?? ?{
?? ??? ?perror("關(guān)閉文件指針失敗");
?? ??? ?exit(1);
?? ?}
?? ?else
?? ?{
?? ??? ?printf("命令【%s】子進(jìn)程結(jié)束狀態(tài)【%d】命令返回值【%d】\r\n", command, rc, WEXITSTATUS(rc));
?? ?}
?? ?return 0;
}
持續(xù)輸出
/*取得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;
?? ?/*將要執(zhí)行的命令寫入buf*/
?? ?snprintf(command, sizeof(command), "ping 192.168.0.101");
?? ?/*執(zhí)行預(yù)先設(shè)定的命令,并讀出該命令的標(biāo)準(zhǔn)輸出*/
?? ?fp = popen(command, "r");
?? ?if(NULL == fp)
?? ?{
?? ??? ?perror("popen執(zhí)行失敗!");
?? ??? ?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);
?? ?}
?? ?/*等待命令執(zhí)行完畢并關(guān)閉管道及文件指針*/
?? ?rc = pclose(fp);
?? ?if(-1 == rc)
?? ?{
?? ??? ?perror("關(guān)閉文件指針失敗");
?? ??? ?exit(1);
?? ?}
?? ?else
?? ?{
?? ??? ?printf("命令【%s】子進(jìn)程結(jié)束狀態(tài)【%d】命令返回值【%d】\r\n", command, rc, WEXITSTATUS(rc));
?? ?}
?? ?return 0;
}
?
?
新人創(chuàng)作打卡挑戰(zhàn)賽發(fā)博客就能抽獎(jiǎng)!定制產(chǎn)品紅包拿不停!總結(jié)
以上是生活随笔為你收集整理的管道popen和pclose的实例使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: gezabo变黑闪退,报错[gazebo
- 下一篇: 10. OD-VC程序暴力破解