C 用exec() 和fork() 对String 数组进行排序;
C Sorting of String arrays with exec() and fork ();
有人可以向我解释一下 for()
和 exec()
是如何调用 sort
这样的系统调用的吗?我一直在阅读,但仍然很困惑。我的数据存储在 .txt 文件中,如下所示:
00-11-D9-20-AA-4E 951
CC-3A-61-DF-4B-61 259
84-1B-5E-A8-BF-7F 82
74-E2-F5-17-96-89 829
84-1B-5E-A8-BF-7C 56
中间的 space 是制表符分隔的。我正在尝试根据 exec()
和 sort()
递减的第二个字段来整理值。但不知道该怎么做。我已调用 fork()
在单独的过程中完成排序。然后,返回父级将结果打印到控制台。
int pid;
FILE *data;
char line[LINESIZE];
data = fopen("results.txt", "r");
switch(pid = fork()){
case -1:
perror("fork()");
exit(1);
break;
case 0:
break;
default:
sleep(3);
while(fgets(line, sizeof line, data) != NULL){
printf("%s", line);
}
printf("arrived at parent");
break;
}
fflush(stdout);
exit(EXIT_SUCCESS);
我做完了,你可以试试
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#define LINESIZE 1024
int main()
{
int pid;
FILE *data;
int fd;
char line[LINESIZE];
data = fopen("results.txt","r");
switch(pid=fork())
{
case -1:
perror("fork()");
exit(1);
break;
case 0:
fd = open("results.txt",O_WRONLY);
dup2(fd,1); //output redirection from stdout to results.txt
execl("/usr/bin/sort",".","a.txt[=10=]",NULL);
break;
default:
sleep(3);
while(fgets(line,sizeof(line),data) != NULL)
{
printf("%s",line);
}
printf("arrived at parent");
break;
}
return 0;
}
有人可以向我解释一下 for()
和 exec()
是如何调用 sort
这样的系统调用的吗?我一直在阅读,但仍然很困惑。我的数据存储在 .txt 文件中,如下所示:
00-11-D9-20-AA-4E 951
CC-3A-61-DF-4B-61 259
84-1B-5E-A8-BF-7F 82
74-E2-F5-17-96-89 829
84-1B-5E-A8-BF-7C 56
中间的 space 是制表符分隔的。我正在尝试根据 exec()
和 sort()
递减的第二个字段来整理值。但不知道该怎么做。我已调用 fork()
在单独的过程中完成排序。然后,返回父级将结果打印到控制台。
int pid;
FILE *data;
char line[LINESIZE];
data = fopen("results.txt", "r");
switch(pid = fork()){
case -1:
perror("fork()");
exit(1);
break;
case 0:
break;
default:
sleep(3);
while(fgets(line, sizeof line, data) != NULL){
printf("%s", line);
}
printf("arrived at parent");
break;
}
fflush(stdout);
exit(EXIT_SUCCESS);
我做完了,你可以试试
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#define LINESIZE 1024
int main()
{
int pid;
FILE *data;
int fd;
char line[LINESIZE];
data = fopen("results.txt","r");
switch(pid=fork())
{
case -1:
perror("fork()");
exit(1);
break;
case 0:
fd = open("results.txt",O_WRONLY);
dup2(fd,1); //output redirection from stdout to results.txt
execl("/usr/bin/sort",".","a.txt[=10=]",NULL);
break;
default:
sleep(3);
while(fgets(line,sizeof(line),data) != NULL)
{
printf("%s",line);
}
printf("arrived at parent");
break;
}
return 0;
}