ฉันกำลังพยายามแปลอักขระขนาดเล็กทั้งหมดของไฟล์ให้เป็นตัวพิมพ์ใหญ่หลังโดยใช้คำสั่ง tr พร้อมการเรียกระบบ exec ของ unix
execl("/usr/bin/tr","tr [a-z] [A-Z] ‹ emp.lst",NULL);
ฉันกำลังพยายามแปลอักขระขนาดเล็กทั้งหมดของไฟล์ให้เป็นตัวพิมพ์ใหญ่หลังโดยใช้คำสั่ง tr พร้อมการเรียกระบบ exec ของ unix
execl("/usr/bin/tr","tr [a-z] [A-Z] ‹ emp.lst",NULL);
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <unistd.h>
#include <ctype.h>
#define MAX 5000
int main( int argc, char *argv[])
{ int pipen[2];
pipe(pipen);
int pipe2[2];
pipe(pipe2);
char buf[MAX];
pid_t child_pid;
if((child_pid = fork()) < 0 )
{
perror("fork failure");
exit(1);
}
if(child_pid == 0)
{
close(pipen[1]);
close(pipe2[0]);
dup2(pipen[0],0);
dup2(pipe2[1],1);
close(pipen[0]);
close(pipe2[1]);
execl("/usr/bin/tr","/usr/bin/tr","[:lower:]", "[:upper:]",NULL);
}
else
{
FILE* inputfile;
inputfile = fopen("in","r");
char c;
if (inputfile) {
int i=0;
while ((c = getc(inputfile)) != EOF){
buf[i]=c;
i++;
if(i>=MAX){break;
buf[i-1]='\0';
}
}
buf[i]='\0';
fclose(inputfile);
}
close(pipen[0]);
close(pipe2[1]);
write(pipen[1],buf,sizeof(buf));
close(pipen[1]);
read(pipe2[0],&buf,sizeof(buf));
close(pipe2[1]);
printf("----->\n%s\n",buf);
}
return 0;
}
นี่เป็นวิธีหนึ่งในการแก้ปัญหานี้ ดังที่ฉันรู้ว่าเราสามารถเขียนได้โดยตรง
execl("/bin/ls","ls","/home/Martin/Documents","-l",NULL); or something but cant
เขียนคำสั่ง tr โดยตรงที่คุณพูดถึง นั่นคือเหตุผลที่ฉันใช้การเรียกระบบ dup2 และ fork เพื่อทำงานตามที่คุณต้องการ ฉันยังใหม่กับสิ่งเหล่านี้ หากมีอะไรผิดพลาดโปรดอธิบายเพิ่มเติม :)