Why does FT_Read () fail in the child process but work in the parent process?

I have the following program that uses the ftd2xx library to write a byte to a USB device and then reads the response.

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdarg.h>
#include "../ftd2xx.h"

void fatal (const char *format,...) {
  va_list argp;
  fprintf(stderr, "FATAL: ");
  va_start(argp, format);
  vfprintf(stderr, format, argp);
  va_end(argp);
  fprintf(stderr, "\n");
  exit(3);
}

int main(int argc, char* argv[]) {
  int pid = fork();
  if (pid > 0) { //replace with: if (pid == 0) {
    FT_STATUS ftStatus;
    printf("before FT_OpenEx\n");
    FT_HANDLE ftHandle;  
    if ((ftStatus = FT_OpenEx("DA011SCV", FT_OPEN_BY_SERIAL_NUMBER, &ftHandle)) != FT_OK) fatal("FT_OpenEx failed");
    printf("before FT_Write\n");
    uint8_t buffer[1];
    buffer[0] = 0x55;
    DWORD bytesWritten;
    if ((ftStatus = FT_Write(ftHandle, buffer, sizeof(buffer), &bytesWritten)) != FT_OK) fatal("FT_Write failed");
    printf("before FT_Read\n");
    DWORD bytesRead;
    if ((ftStatus = FT_Read(ftHandle, buffer, 1, &bytesRead)) != FT_OK) fatal("FT_Read failed");
    if (bytesRead > 0) {
      printf("FT_Read data=0x%02X\n", buffer[0]);
    } else {
      printf("FT_Read no data\n");
    }
    printf("before FT_Close\n");
    if ((ftStatus = FT_Close(ftHandle)) != FT_OK) fatal("FT_Close failed");
    printf("press Enter to exit\n");
  }
  getchar();
  exit(0);
}

The code shown below outputs this result:

//Output if (pid > 0)
before FT_OpenEx
before FT_Write
before FT_Read
FT_Read data=0x55
before FT_Close
press Enter to exit

However, if I change the condition of the first iffrom (pid > 0)to (pid == 0), i.e. if I do USB communication in a child process, the program freezes in a function FT_Read()and the output is:

//Output if (pid == 0)
before FT_OpenEx
before FT_Write
before FT_Read

Why is this happening?

Some information:

  • The USB chip in the device is an FT240X with factory settings.
  • The USB device acts like an echo: every byte it receives is immediately sent back.
  • I checked with the protocol analyzer the correct values ​​for the transmitted bytes.
  • The version of the ftd2xx library is 1.1.12.
+3
2

, , ftd2xx - , , .

ftd2xx , , , . , FTDI , libftdi.

+2
0

Source: https://habr.com/ru/post/1673079/


All Articles