- 论坛徽章:
- 0
|
我想在c里调用ftp进行文件传输,并且对传输结果进行判断(失败还是成功):
于是在网上找到了一个程序,其基本思想就是由进程启动一个子进程,然后在子进程内execl ftp命令。同时在父进程内开通两个管道一个用来向ftp发送命令(put,get)另外一个用来接收ftp的输出。最后我通过ftp的输出来判断传送文件是否成功。但有个问题:我传送的文件有些比较大也有一些小文件。poll函数的timeout参数设成永久等待后程序好像不动了。如果timeout参数设成常数传送大文件时又可能得不到ftp命令的输出。请高手救命!程序代码如下:
#include <unistd.h>;
#include <poll.h>;
#include <stdlib.h>;
#include <stdio.h>;
int sendcmd();
main(argc,argv)
{
int fd1[2], fd2[2];
pid_t pid;
char buf[1024];
if (pipe(fd1)<0 || pipe(fd2)<0)
return(-1);
if ((pid=fork())<0)
return(-2);
if (!pid)
{ /* child */
close(fd1[1]);
close(fd2[0]);
dup2(fd1[0], STDIN_FILENO); /* join child's stdin to parent's fd1[1] */
dup2(fd2[1], STDOUT_FILENO); /* join child's stdin to parent's fd2[0] */
close(STDERR_FILENO); /* discard child's stderr */
close(fd1[0]);
close(fd2[1]);
if (execl("/usr/bin/ftp", "ftp", "-ivn", NULL)<0)
perror(NULL);
exit(0);
}
close(fd1[0]);
close(fd2[1]);
sendcmd(fd1[1], fd2[0], "open 10.238.17.0\n", buf, sizeof(buf));
sendcmd(fd1[1], fd2[0], "user username password\n", buf, sizeof(buf));
sendcmd(fd1[1], fd2[0], "bin\n", buf, sizeof(buf));
sendcmd(fd1[1], fd2[0], "mput lc*\n", buf, sizeof(buf));
sendcmd(fd1[1], fd2[0], "by\n", buf, sizeof(buf));
close(fd1[1]);
close(fd2[0]);
return(0);
}
int sendcmd(fo, fi, cmd,buf, size)
int fo;
int fi;
char *cmd;
char *buf;
size_t size;
{
int n=0;
struct pollfd fds[1];
fds[0].fd=fi;
fds[0].events=POLLRDNORM;
fds[0].revents=0;
write(fo, cmd, strlen(cmd)); /* send command */
while(poll(fds, 1, INFTIM)>;0)
{
int t;
if(!(t=read(fi,&buf[n],size)))
break;
n+=t;
}
buf[n]=0;
printf("%s", buf);
fflush(stdout);
return(0);
} |
|