问题描述
如何将 #include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>
int main(int argc,char *argv[]) {
int fds[2];
int test[2];
int pid;
pid_t child_a;
char buffer[50],buff[50];
if(pipe(fds)) {
perror("Pipe:");
exit(0);
}
if(pipe(test)) {
perror("Pipe:");
exit(0);
}
child_a = fork();
if (child_a == 0) {
//Child
//CHANGED: No need to open file pointers here. Pipes are already open and accessed by file descriptor instead of file pointer. File pointers create trouble when used with pipes. 0 is file descriptor of stdin,1 for stdout.
close(fds[1]);
close(test[0]);
dup2(fds[0],0);
dup2(test[1],1);
//CHANGED: There was an error with the command you wrote.
//That's because ./sand arg will look for a 'sand' directory which doesn't exist
//This line will throw warnings because execlp requires needs a command as the second argument,but in this case the filename is the command.
//NOTE: before running quick.c,compile sand.c as sand.out and not a.out
execlp("./sand.out",NULL);
printf("Exec Error\n"); //this will only execute if execlp didn't run. Always have this line in your code to kNow what's happening.
}
else
{
// Parent
// Wrap the pipes
//Got rid of the file pointers
close(fds[0]);
close(test[1]);
//CHANGE: fgets is only used with file pointers. While handling pipes,we work with file descriptors,with which read and write methods are used
int n = read(0,buffer,50); //If this is new to you,I strongly recommend reading manual pages for read and write,but for right Now
// The signature should be enough to understand - read/write(int file_descriptor,char *buffer,int number_of_bytes)
write(fds[1],n);
//MOST IMPORTANT: You need to wait for child after this point. Because test pipe doesn't have data yet which will be received by child.
wait(NULL);
//CHANGE: printf statements do not work well with buffere,because buffers are not terminated with null
//%s specifier will always look for a null or print garbage
//If you still want to use printf,look into $man bzero
while((n = read(test[0],buff,50))>0)
{
write(1,n);
}
fflush(stdout);
}
return 0;
}
列类型从对象转换为
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc,char *argv[])
{
char buffer[50];
int i = 0;
int n = read(0,sizeof(buffer)); //changed fgets to read,to get number of bytes read.
char chr;
// Loop
// we have number of bytes. So change while to for
for (i=0;i<n;i++)
{
buffer[i] = toupper(buffer[i]);
}
write(1,n); //Changed fprintf to write to get rid of %s problem.
//Again,to fill remaining places of buffer with null,look up bzero.
//The reason I haven't done that is to not confuse you with so many changed methods.
return 0;
}
?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)