working named pipe and pipe simple with c and golang

This commit is contained in:
talksik
2023-11-21 09:11:47 -08:00
commit 61a43bd732
10 changed files with 178 additions and 0 deletions
+42
View File
@@ -0,0 +1,42 @@
package main
import (
"fmt"
"os"
"syscall"
)
// createNamedPipe creates a named pipe (FIFO)
func createNamedPipe(pipeName string) error {
err := syscall.Mkfifo(pipeName, 0666)
if err != nil && !os.IsExist(err) {
return err
}
return nil
}
func main() {
// Create a named pipe (FIFO)
pipeName := "my_pipe"
err := createNamedPipe(pipeName)
if err != nil {
fmt.Println("Error creating named pipe:", err)
return
}
// Open the named pipe for writing
pipe, err := os.OpenFile(pipeName, os.O_WRONLY, os.ModeNamedPipe)
if err != nil {
fmt.Println("Error opening named pipe for writing:", err)
return
}
defer pipe.Close()
// Write data to the named pipe
message := "Hello from the writer program!"
_, err = pipe.WriteString(message)
if err != nil {
fmt.Println("Error writing to named pipe:", err)
return
}
}
+34
View File
@@ -0,0 +1,34 @@
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main() {
const char *pipeName = "my_pipe";
// Open the named pipe for reading
int fd = open(pipeName, O_RDONLY);
if (fd == -1) {
perror("Error opening named pipe for reading");
return 1;
}
// Read data from the named pipe
char buffer[100];
ssize_t bytesRead = read(fd, buffer, sizeof(buffer));
if (bytesRead == -1) {
perror("Error reading from named pipe");
close(fd);
return 1;
}
// Print the received data
printf("Data read from the named pipe: %.*s\n", (int)bytesRead, buffer);
// Close the named pipe
close(fd);
return 0;
}
Binary file not shown.
Binary file not shown.