有人可以帮我制作这个 C POSIX 代码来移植它以在 Windows 下运行吗?(没有 Cygwin,MinGW 只是 Windows 本机 API 和 Visual Studio),尝试了很多事情,但没有任何运气。
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <stdlib.h>
void usage(char *s);
int test_function(char *host);
FILE *infile, *outfile;
int numforks = 0;
void usage(char *s) {
printf("Usage: %s <input> <childs>\n", s);
exit(EXIT_SUCCESS);
}
int main(int argc, char *argv[]) {
char buf[1024];
time_t start;
if (argc < 2)
usage(argv[0]);
outfile = fopen("test.txt", "a+");
infile = fopen(argv[1], "r");
printf("[*] In: %s Childs: %s\n", argv[1], argv[2]);
start = time(0);
while (!feof(infile)) {
fgets((char *)&buf, sizeof(buf), infile);
if (buf[strlen (buf) - 1] == '\n')
buf[strlen (buf) - 1] = '\0';
if (!(fork())) {
test_function(buf);
exit(0);
} else {
numforks++;
if (numforks > atoi(argv[2]))
for (numforks; numforks > atoi(argv[2]); numforks--)
wait(NULL);
}
}
fclose(infile);
fclose(outfile);
printf("[*] Completed in: %lu secs\n", (time(0) - start));
exit(EXIT_SUCCESS);
}
int test_function(char *host) {
usleep(2000000); // for debugging
fprintf(outfile, "%s\n", host);
printf("%s\n", host);
return 1;
}
我试图这样做:
#include <stdio.h>
#include <string.h>
#ifdef LINUX
#include <unistd.h>
#endif
#include <time.h>
#include <stdlib.h>
#ifdef WIN32
#define fork _forkWin32
#define usleep Sleep
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <process.h>
#include <windows.h>
using namespace std;
#endif
void usage(char *s);
#ifdef WIN32
unsigned int _stdcall test_function(void *ptr);
#else
int test_function(char *host);
#endif
FILE *infile, *outfile;
int numforks = 0;
char proc;
void usage(char *s) {
printf("Usage: %s <input> <threads>\n", s);
exit(EXIT_SUCCESS);
}
int main(int argc, char *argv[]) {
char buf[1024];
time_t start;
//#ifdef WIN32
//HANDLE child;
//#endif
if (argc < 3)
usage(argv[0]);
outfile = fopen("test.txt", "a+");
infile = fopen(argv[1], "r");
printf("[*] In: %s Threads: %s\n", argv[1], argv[2]);
start = time(0);
HANDLE child;
while (!feof(infile)) {
fgets((char *)&buf, sizeof(buf), infile);
if (buf[strlen (buf) - 1] == '\n')
buf[strlen (buf) - 1] = '\0';
#ifdef WIN32
child = (HANDLE) _beginthreadex(NULL, 0, test_function, buf, 0, NULL);
if (child != 0) {
#else
if (!(fork())) {
test_function(buf);
#endif
exit(0);
} else {
numforks++;
if (numforks > atoi(argv[2]))
for (numforks; numforks > atoi(argv[2]); numforks--)
#ifdef WIN32
WaitForSingleObject(child, INFINITE);
#else
wait(NULL);
#endif
}
}
fclose(infile);
fclose(outfile);
printf("[*] Completed in: %lu secs\n", (time(0) - start));
exit(EXIT_SUCCESS);
}
#ifdef WIN32
unsigned int test_function(void *ptr) {
char* host = (char*)ptr;
#else
int test_function(char *host) {
#endif
usleep(2000000); // for debugging
fprintf(outfile, "%s\n", host);
printf("%s\n", host);
return 1;
}
似乎什么都没做。我究竟做错了什么?都错了吗?