資源簡介
使用fork(),exec(),dup2(), pipe(),open()系統調用完成與下列shell命令等價的功能:grep -v usr result.txt
代碼片段和文件信息
#include?
#include?
#include?
#include?
#include?
#include?
#include?
#define?MAX_PARA_NO?128
int?main()
{
????int?n?pfd[2];
????char?buffer[128]?=?““;
????char?*in?*out?*buffer2?*cmd1?*cmd2;
????char?*para1[MAX_PARA_NO]?*para2[MAX_PARA_NO];
????strcpy(buffer?“grep?-v?usr?/etc/passwd?|?wc?-l?>?result.txt“);//待處理命令
????signal(SIGCLD?SIG_DFL);//忽略SIGCLD信號,子進程終止后,系統會自動銷毀僵尸子進程
????buffer2?=?strstr(buffer?“|“);//定位管道位置
????in?=?strstr(buffer?“<“);?//定位重定向輸入文件位置
????out?=?strstr(buffer?“>“);//定位重定向輸出文件位置
????if?(in)?{
????????*in?=?‘\0‘;
????????in?=?strtok(in?+?1?“?<>\t\n“);//獲取輸入重定向文件名
????}
????if?(out)?{
????????*out?=?‘\0‘;
????????out?=?strtok(out?+?1?“?<>\t\n“);//獲取輸出重定向文件名
????}
????if?(!?buffer2)
????????exit(0);
????else?{
????????*buffer2?=?‘\0‘;
????????buffer2++;
????}
????cmd2?=?strtok(buffer2?“?<>\t\n“);//獲取第二個命令
????if?(!?cmd2)
????????exit(1);
????//獲取第二個命令及選項
????para2[0]?=?cmd2;?
????for?(n?=?1;?para2[n];?n++)?{
????????para2[n]?=?strtok(N
評論
共有 條評論