1, 使用pipe創建一個管道,並使用fork()創建一個子進程;
2, 父進程關閉管道的寫端,子進程關閉管道的讀端(思考爲什麼?)
3, 子進程重定向標準輸出爲管道的寫端(想想上一次佈置的任務怎麼做重定向)
4, 子進程執行ifconfig eth0命令,這時命令的輸出將會輸出到到管道上;
5, 父進程從管道里讀取字符串,並用字符串解析函數獲取到IP地址
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
#include <errno.h>
#define maxsize 1024
/********************************************************************************
* Description:
* Input Args:
* Output Args:
* Return Value:
********************************************************************************/
int main (int argc, char **argv)
{
size_t n;
int i = 0, m = 0;
int fd[2];
pid_t pid;
FILE *fp;
char line[maxsize];
char *pipe_buf = NULL;
char *get_buf[maxsize];
char *addr_buf = NULL;
char *ipaddr[2];
if (pipe(fd) < 0)
{
printf("pipe failure: %s\n", strerror(errno));
exit(-1);
}
if ((pid = fork()) < 0)
{
printf("fork() failure: %s\n", strerror(errno));
exit(-1);
}
else if (pid > 0)
{
close(fd[1]); /* close write */
memset(line, 0, maxsize);
if ((n = read(fd[0], line, maxsize)) < 0)
{
printf("read failure: %s\n", strerror(errno));
exit(-1);
}
pipe_buf = line; /* read string from pipe */
while ((get_buf[i] = strtok(pipe_buf, " ")) != NULL)
{
i++;
pipe_buf = NULL;
}
i = 0;
while (get_buf[i] != NULL)
{
if ((addr_buf = strstr(get_buf[i], "addr:")) !=NULL)
{
ipaddr[m++] = addr_buf;
}
i++;
} /* analysis string "addr:xxx.xxx.xxx.xxx" from eth0 */
i = 0;
addr_buf = ipaddr[0];
while ((ipaddr[i] = strtok(addr_buf, ":")) != NULL)
{
i++;
addr_buf = NULL;
} /* analysis ipaddr "xxx.xxx.xxx.xxx" from "addr:xxx.xxx.xxx.xxx"*/
addr_buf = ipaddr[1]; /* ipaddr */
printf("%s\n", addr_buf);
close(fd[0]);
if (waitpid(pid, NULL, 0) < 0)
{
printf("wait for child process failure: %s\n", strerror(errno));
exit(-1);
}
exit(0);
} /* else if */
else /*client */
{
close(fd[0]); /* close read */
if (fd[1] != STDOUT_FILENO)
{
if (dup2(fd[1],STDOUT_FILENO) != STDOUT_FILENO)
{
printf("copy STDOUT_FILENO to fd[1] failure: %s\n", strerror(errno));
return(-1);
}
close(fd[1]);
}
if (execl("/sbin/ifconfig", "ifconfig", "eth0", (char *)0 ) < 0)
{
printf("execl failure: %s\n", strerror(errno));
exit(-1);
}
}
return 0;
} /* ----- End of main() ----- */
基本功能能實現,就是代碼有點繁瑣.菜鳥一隻.以後還要多加努力.本來是要求弄成函數的,但是自己懶,不想去弄了. 要想弄成函數直接返回buf_addr就可以了