libzypp 17.37.17
linuxhelpers.cc
Go to the documentation of this file.
2
3#include <zypp-core/zyppng/io/SockAddr>
4#include <zypp-core/zyppng/base/Timer>
5
6#include <pthread.h>
7#include <csignal>
8#include <iostream>
9#include <unistd.h>
10#include <sys/ioctl.h>
11#include <fcntl.h>
12
13namespace zyppng {
14
16 {
17 sigset_t set;
18 ::sigfillset(&set);
19 int res = ::pthread_sigmask(SIG_BLOCK, &set, NULL);
20 return ( res == 0 );
21 }
22
23 bool blockSignalsForCurrentThread( const std::vector<int> &sigs )
24 {
25 sigset_t set;
26 ::sigemptyset(&set);
27 for ( const int sig : sigs )
28 ::sigaddset( &set, sig );
29
30 int res = ::pthread_sigmask(SIG_BLOCK, &set, NULL);
31 return ( res == 0 );
32 }
33
34 bool trySocketConnection( int &sockFD, const SockAddr &addr, uint64_t timeout )
35 {
36 int res = -1;
37 const auto opStarted = zyppng::Timer::now();
38 do {
39 res = zyppng::eintrSafeCall( ::connect, sockFD, addr.nativeSockAddr(), addr.size() );
40 if ( res < 0 && errno != ECONNREFUSED && errno != EADDRNOTAVAIL ) {
41 ERR << "Connection failed with error: " << errno << " " << zyppng::strerr_cxx( errno ) << std::endl;
42 ::close( sockFD );
43 sockFD = -1;
44 return false;
45 }
46 } while ( res == -1 && zyppng::Timer::elapsedSince( opStarted ) < timeout );
47 return ( res == 0 );
48 }
49
50 void renumberFd (int origfd, int newfd)
51 {
52 // It may happen that origfd is already the one we want
53 // (Although in our circumstances, that would mean somebody has closed
54 // our stdin or stdout... weird but has appened to Cray, #49797)
55 if (origfd != newfd)
56 {
57 dup2 (origfd, newfd);
58 ::close (origfd);
59 }
60 }
61
62 int64_t bytesAvailableOnFD( int fd )
63 {
64 int value = 0;
65 if ( ioctl( fd, FIONREAD, &value) >= 0 )
66 return int64_t(value);
67
68 return 0;
69 }
70
71 std::optional<Pipe> Pipe::create( int flags )
72 {
73 int pipeFds[]={ -1, -1 };
74
75#ifdef HAVE_PIPE2
76 if ( ::pipe2( pipeFds, flags ) != 0 )
77 return {};
78#else
79 if ( ::pipe( pipeFds ) != 0 )
80 return {};
81 if ( flags != 0 ) {
82 ::fcntl( pipeFds[0], F_SETFD, flags );
83 ::fcntl( pipeFds[1], F_SETFD, flags );
84 }
85#endif
86 return Pipe {
87 .readFd = zypp::AutoFD( pipeFds[0] ),
88 .writeFd = zypp::AutoFD( pipeFds[1] )
89 };
90 }
91
92}
virtual struct::sockaddr * nativeSockAddr() const =0
virtual std::size_t size() const =0
static uint64_t elapsedSince(const uint64_t start)
Definition timer.cc:83
static uint64_t now()
Definition timer.cc:70
bool blockAllSignalsForCurrentThread()
bool trySocketConnection(int &sockFD, const SockAddr &addr, uint64_t timeout)
bool blockSignalsForCurrentThread(const std::vector< int > &sigs)
auto eintrSafeCall(Fun &&function, Args &&... args)
int64_t bytesAvailableOnFD(int fd)
void renumberFd(int origfd, int newfd)
std::string strerr_cxx(const int err=-1)
AutoDispose<int> calling close
static std::optional< Pipe > create(int flags=0)
#define ERR
Definition Logger.h:102